Search code examples
c++ifstreamnan

ifstream: Skip reading lines containing NaN


I'm reading a text file using ifstream on VS2012 C++. Is there a simple way to skip reading lines that contain "NaN"?

ifstream loadFile;
loadFile.open("data.txt", ios::in);

double x;
int numLine = 3;
int numCol = 4;
vector< vector<int> > data(numLine, vector<int> numCol);

for( int i=0; i< numLine; i++){
    for ( int j=0; j< numCol; j++){
        loadFile >> x ;
        data[i][j] = x;
    }
} 

File sample:

2.4 4.6 6.8 0.34
5.34 3.4 NaN 1.1 
2 -4 -6 5 

Solution

  • It's hard to detect that the input string was literally "NaN" but you can do

    if (!(loadFile>>x)) // Read might fail on "NaN"
    {
        loadFile.clear(); // Reset error state
        loadFile.ignore(3); // This assumes we only fail on NaN.
    }
    

    This ignores just the single input. Of course, if your input can contain -NaN or other inputs with length!=3 then you need to be a bit smarter. And if you need to ignore the whole line, then you need to reset i after the bad line.