How to Read Until Eof from Cin in C++

Read input from istream until EOF

You are using the while loop incorrectly.

Use:

int main(int argc, char **argv)
{
int num = 0;

// Keep reading from stdin until EOF is reached or
// there is bad data in the input stream.
while ( cin >> num )
{
if(isPrime(num)){
cout << "prime\n";
} else {
cout << "composite\n";
}
}

return 0;

} // end main

Read cin till EOF

On http://ideone.com you can provide input on the "input" tab. Anything inputted into this box will be fed to cin appended with an eof character.

For example if you do:

while (cin.get() != decltype(cin)::traits_type::eof());

On your local machine that will never come back till you press Ctrl + z and press Enter But on http://ideone.com it will always return after parsing everything typed into the "input" tab.

Reading from text file until EOF repeats last line

Just follow closely the chain of events.

  • Grab 10
  • Grab 20
  • Grab 30
  • Grab EOF

Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.

Try this:

while (true) {
int x;
iFile >> x;
if( iFile.eof() ) break;
cerr << x << endl;
}

By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.

How to use input redirection with a special integer as divider and until eof

You can use the fact that ifstream::operator bool () returns false at EOF to terminate your loops.

Code (modified to use std::list):

std::list <int> L1, L2;
int x;

while(std::cin >> x)
{
L1.push_back(x);//Function to add to linked list
if (x==99999) break; //Attempt at ignoring 99999
}

while(std::cin >> x)
L2.push_back(x);

Live demo



Related Topics



Leave a reply



Submit