I am learning C++ and have come across something that is confusing me. My goal is to read in a file, add some things to it, take some input then output all of this to a new file.
The problem is whenever I output all of the modified data, it will either output an extra line that I don't want, or it will output one less line than I want. For example, the input file will contain:
1 2 3
LineA
LineB
LineC
The output will be either:
1 2 3 4
:
LineA:
LineB:
LineC:
or:
1 2
LineB:
LineC:
I believe this problem is occurring in the for loop. I've tried changing the b value to 1 or 0 and both will not give me what I want.
The reason is that the EOF flag is not set until AFTER the read fails. So doing it your way will add at leas one input to the array before the end of file is detected.
#include<iostream.h>
#include<fstream.h>
#include<cstring.h>
void main()
{
ifstream file;
file.open("D:qabil.txt");
string temp;
getline(file,temp);//you can do this step until line you want
getline(file,temp,1);
cout<<temp;
}
and now it works. I don't completely understand why this was causing a problem, but after studying fstream a bit more, I noticed I was adding my argv[2] twice previously. One time before the for loop with ofstream and one time during the loop with open. Why would this cause an issue for what I was attempting?