I have a text file, which stores some data. There are several blocks of data formatted in different ways, so I need my program to be able to tell when one block ends and another one starts. Here is a very simple example.
Text file:
a 1
b 2
c 3
qwerty
asdfgh
xcvbnm
My program:
int x;
char a;
string line;
while(ifs >> a >> x)
cout << a << " " << x << "\n";
cout<<"\n" << "next block of data" << "\n";
while(ifs >> line)
cout << line;
However it does not read the second half. I thought that formatted reading with >> just discards whitespaces, so I thought that after the first while() fails, the second while() should start reading the second half. Here is my output:
a 1
b 2
c 3
next block of data
Also, if anybody can recommend something to read about this, I would be the most grateful. I searched several books and internet and couldn't find any clear manual about how the >> operator works.
When operator>>
fails, fail bit is set, and all sebsequent extraction will fail, too, unless you clear the error flags. Use ios::clear()
while(ifs >> a >> x)
cout << a << " " << x << "\n";
ifs.clear();
You can use ios::bad()
, ios::fail()
and ios::eof()
to determine why the extraction failed, so you can act accordingly.