Originally Posted by
sting777
I am trying to parse a code textfile using getline but it always discards the newline character and inserts a null, I want to know if their is an easy way to append a newline to the end of the string overwriting the null character when writing the outputfile. If I use getline in and I try to output myfile << line; it just creates line of text when you open it in a text editor because their is no newlines.
Originally in the examples I was reading from, I was reading and writing text files character by character and the files would copy exactly, but using string functions on files means the formatting of the file gets lost.
I'm not sure if I'm using the right class to be doing text parsing but basically I just want to parse the file so I can change the numerical values in text mode and then re-output the file.
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
string filepath = "";
if (argc == 2) {
filepath = argv[1];
}
else {
cout<< "Error! You did not pass a filepath." <<endl;
return 1;
}
char buf[50];
string bufString = "";
ifstream filestreamInObject(filepath);
if (!filestreamInObject.is_open()) {
cout<< "Error! File was not opened.\n"
"Please make sure you passed a valid filepath." <<endl;
return 1;
}
while (!filestreamInObject.eof()) {
filestreamInObject.getline(buf, sizeof(buf));
bufString = buf;
bufString += '\n';
}
cout<< "You read from file:\n" << bufString <<endl;
cout<< "\n\nPress Enter to end this program." <<endl;
cin.get();
return 0;
}