Dynamic memory help (array of char)
Feb 8, 2014 at 11:15am UTC
General Purpose: Delete all "white spaces" in text file, until the read-in char is _not_ a whitespace (mark as start of text file).
Problem: Cannot seem to shift char's over properly. (I think my problem is the inner loop - however other code may lead to this problem - I do not know)
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <fstream>
#include <iostream>
using namespace std;
bool trimWhiteSpace(fstream &file, char * charMemoryBlock) {
if (!file.is_open()) {
return false ;
}
streampos posInFile = file.tellg();
int fileSize = posInFile;
file.seekg(0, ios::beg);
file.read(charMemoryBlock, posInFile);
for (int i = 0; i < fileSize; i++) {
if (isspace(charMemoryBlock[i])) {
fileSize--;
// ?
for (int j = i; j < fileSize; j++) {
charMemoryBlock[j] = charMemoryBlock[j + 1];
}
// ?
} else {
cout << "Trim White Space = COMPLETE, i = " << i << endl;
cout << "Char value exited on = " << charMemoryBlock[i] << endl;
return true ;
}
}
}
int main () {
fstream file("foo.txt" , ios::in | ios::binary | ios::ate);
char * memblock = new char [file.tellg()];
trimWhiteSpace(file, memblock);
file.close();
// Test the output, to see if whitespaces are deleted
for (int i = 0; i < 15; i++) {
cout << memblock[i];
}
delete [] memblock;
return 0;
}
Feb 8, 2014 at 11:56am UTC
1 2 3 4 5 6 7 8 9 10 11 12
#include <fstream>
int main()
{
std::ifstream file( "foo.txt" ) ;
char c ;
if ( file >> c ) file.putback(c) ; // read and put back the first non-ws character
// copy everything from the first non-ws character onwards to foo.trimmed.txt
std::ofstream ( "foo.trimmed.txt" ) << file.rdbuf() ;
}
Feb 9, 2014 at 2:18am UTC
Wow Thanks a lot JLBorges, the more you know!
Also; any simple command in fstream library to put the file into the dynamic char array?
Cheers,
-fratello
Feb 9, 2014 at 3:46am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <fstream>
#include <string>
#include <iterator>
#include <iostream>
int main()
{
std::ifstream file( "foo.txt" ) ;
// copy everything from the first non-ws character onwards into a string
// http://www.cplusplus.com/reference/istream/ws/
std::istreambuf_iterator<char > first_non_ws( file >> std::ws ), eof ;
const std::string ltrimmed( first_non_ws, eof ) ;
std::cout << ltrimmed ;
}
Topic archived. No new replies allowed.