Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through file fail

Tags:

c++

I want to iterate through a file and print all the string. example, the file contain:

a
1
2
10
a1
1
b

will output:

a
a1
b

I write my code like this:

int main(){
  ifstream stream;
  stream.open("example.txt");
  string temp;
  while (getline(stream, temp)){
    cout<<temp<<endl;
    int n;
    while(stream>>n){}
  }
}

this program online print "a" and "a1". and suggestion?

like image 554
Jessica Herlian Avatar asked Jun 14 '26 15:06

Jessica Herlian


2 Answers

What happens is the following: once your program hits this line,

while(stream>>n){}

it attempts reading the following tokens from the file as integers. 1 succeeds. 2 succeeds. 10 succeeds. a1 fails.

stream is now in a fail state (stream.fail() == true). The next statement your code executes is

while (getline(stream, temp)){

This will read the next token (a1) but since stream is in a fail state, the result of getline will be interpreted as false, and the loop will be interrupted.

That’s why your program ends prematurely. However, it shouldn’t even print a1. Indeed, it only prints a on my machine.

You need to clear the fail state after eating the integer tokens inside the loop. Add the following statement at the end:

stream.clear();

This resets the fail state (stream.fail() == false) and the outer loop will continue to run.

like image 141
Konrad Rudolph Avatar answered Jun 17 '26 22:06

Konrad Rudolph


What about this?

std::copy_if(std::istream_iterator<string>(stream), std::istream_iterator<string>(),
             std::ostream_iterator<string>(std::cout),
             [](std::string const& rhs) { return !std::isdigit(rhs[0]); })
like image 22
Alex Chamberlain Avatar answered Jun 18 '26 00:06

Alex Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!