0

I have some beginners questions about file handing and loops. For example, lets say the file contains words and integers. And the logic is to read only the integers from the file. I know the outer loop ends when the pointer is at end of file. But I don't know the conditions that causes the inner loop to break. Does the loop break if it encounters words? if so does it set the file pointer to next line or does the file pointer not move? If the inner loops fails to run the first time, where does it set the file pointer?

here is what's on the file.

some words 11 12 15 14 15 some words 122
some words 45 1 12 2135 words
//here is the logic 
int someInt = 0, counter = 0;
   while (!file.eof()) //Runs until end of file
   {
      while(file >> someInt) //only reads integers. when does this loop break?
       { 
           counter++; 
       }
   }
Ghost001
  • 43
  • 7
  • 2
    [`while (!file.eof())` is an anti-pattern](https://stackoverflow.com/q/5431941/501250). Don't do that. – cdhowie Apr 21 '20 at 18:13
  • `while(file >> someInt)` exits when an `int` cannot be read from the file. Finding the "some words" for example. Note that if you read for an `int` and fail, you'll have to `clear` the error flag before you continue. – user4581301 Apr 21 '20 at 18:18
  • @user4581301 does the file pointer move at all when it finds "some words" in this case or does it not move and halt? – Ghost001 Apr 21 '20 at 18:25
  • @Ghost001 Most likely, the file pointer has advanced well beyond that point due to internal buffering by the file stream. – Remy Lebeau Apr 21 '20 at 18:26
  • The stream stops dead and forces you to deal with the error and whatever data is in the way of you finding the next `int`. If you want to read lines, see [`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline). Read a line with `std::getline` and place the line into a [`std::istringstream`](https://en.cppreference.com/w/cpp/io/basic_istringstream), then parse the `std::istringstream` as you normally would. See [option two in this answer](https://stackoverflow.com/a/7868998/4581301) for an example. – user4581301 Apr 21 '20 at 18:28

0 Answers0