Reputation: 399
Let say, I have file input.txt with few numbers
1 2
4 51
3 77
Now, I was trying to perform this command:
`string filename="input.txt";
ifstream ifs;
ifs.open(filename);
ifs>>x>>y;
fstream tmp("temp.txt",ios::out);
tmp<< ifs.rdbuf(); `
Now the file temp.txt looks like
(empty space)
4 51
3 77
So, is this empty space because, I didn't read end of the line? "ifs" ponter was just moved for two integers, and remaining end of the line was left. Why in the first file, I can loop with
ifs>>x>>y;
and in the second (tmp) not? On the other hand if I manually create temp.txt with empty space, command above immediately works. Why this is inconsistent?
Thanks.
Upvotes: 2
Views: 703
Reputation: 409266
The input operator, when reading e.g. strings and numbers (integers and floating point), skips leading whitespace.
If you want to remove the trailing whitespace after reading the first two numbers, simply ignore
until the end of the line.
Upvotes: 2
Reputation: 129454
Because ifs >> x >> y;
does not read the newline after the numbers on the first line. You could fix it in this particular case by adding ifs.get()
or some such, but in the generic case [e.g. if the file is 1 2 <newline>
, there will still be a bunch of spaces and a newline in the file - just one less than without the get
call, so you'd have to read the input file and determine what is in the file.
As Joachim suggests, you could use ignore
to skip to the next newline, but again, it won't really help if you have more than one newline.
Upvotes: 2