1

I have two files. main.cpp:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream file;
    file.open("file.txt");

    if (!file.good()) {
        cout << "Error." << endl;
        return 1;
    }

    int n;
    while (!file.eof()) {
        file.clear();

        file >> n;
        if (!file.good() && !file.bad()) {
            continue;
        } else {
            cout << "Hardware error." << endl;
            break;
        }
        cout << n << endl;
    }

    file.close();

    return 0;
}

and file.txt:

a 1 2 321b9 ac.de ef#@g 5 #3

I'd like to read only integers from this file and write them out to the console. When file contains only integers program works well but when it contains any invalid characters then I get infinite loop. How can I fix that?

tdudzik
  • 391
  • 4
  • 17

1 Answers1

1

The loop is because the stream doesn't extract the character that is not an integer. You need to extract it before attempting to read another integer.

A small tweak could be all that is needed;

// on a failed read...
file.clear();
char dummy;
file >> dummy;
continue;

A side note on the use of while (!file.eof()); it is generally not recommended to do this. There are several Q&A on SO on this issue.

Niall
  • 30,036
  • 10
  • 99
  • 142