c++ - Confusion with spaces in fileIO -


i have input files this:

734 220 915 927 384 349 79 378 593 46 2 581 500 518 556 771 697 571 891 181 537 455  

and bad input files this:

819 135 915 927 384 349 79 378 593 46 2 581 500 518 556 771 697 551 425 815 978 626 207 931 abcdefg 358 16 875 936 899 885 195 565 571 891 181 537 110  

where there space following last integer @ end of both files. i'm trying write script in c++ read in integers unless there char/string in second example in case alert me of this. tried write this:

int main() { int n; bool badfile = false; ifstream filein("data.txt");  while (!filein.eof()) {     filein >> n;         if(filein.fail())     {         cout << "not integer." << endl;         badfile = true;         break;       }        cout << n << " ";    }  cout << endl << "file check: " << badfile << endl; } 

but filein.fail() triggered space @ end of file char/string in bad file. how can set ignores white spaces? why fail if there's space @ end instead of either failing @ spaces or ignoring them altogether?

the main issue how test eof() on stream... it's set after input attempt tries read more characters when @ end of file. using std::ws first consume whitespace means eof detection can reliable: if you're not @ eof() know you're @ non-whitespace input should number - if not have error in input content.

suggested code:

#include <iostream> #include <fstream> #include <iomanip>  int main() {     if (ifstream filein("data.txt"))     {         while (filein >> std::ws && !filein.eof())         {             int n;             if (filein >> n)                 cout << n << ' ';             else             {                 std::cerr << "error in input\n";                 exit(exit_failure);             }         }         std::cout << '\n';     }     else         std::cerr << "unable open data.txt\n"; } 

an alternative appear below, might easier understand isn't totally reliable. problem can reach eof despite bad input such trailing - or +, that'd consumed while trying read number isn't in enough constitute successful parsing of number. if file known have '\n' terminating last line, reliable:

        int n;         while (filein >> n)             cout << n << " ";            filein.clear();  // remove error state         if (filein.peek() != istream::traits_type::eof())         {             // while didn't reach eof; must parsing error             std::error << "invalid input\n";             exit(exit_failure);         } 

Comments