Search code examples
c++arraysfilestreams

Reading only float values from text file


I have a data file which is text format. It has 2 coloums first one is not useful that I could ignore it and second one is that what I need. The coloum has a different values on each row as string, float etc. For some calculation I need to only float members of this coloum. I followed that way, first declare a float array and read values and save the array with ">>" basic command.

Problem is when non-float row has came, reading function works as broken. It reads non-float values as "0" and save as that. It's OK but after that reads whole values as "0" even if it was a float.

Datafile.txt (example)

aa 1.1
bb 2.2
cc 3.0
dd somestring
ee 4.3
ff 4.9

Code (example)

 do 
{
    dfile >> a >> dat[i]; 
    ofile << dat[i]<<endl;
    cout << dat[i]<<endl;
    i++;

}while(dfile.eof());

Output file (example)

1.1
2.2
3.0
0
0
0
..goes 

I've thought two ways to solve the problem. First one is skipping non-float rows. Second one is reading row in a period. Because float values listed in a sequence.


Solution

  • Read a string first, then attempt to convert to a number:

    std::string maybeNumber;
    while (dfile >> a >> maybeNumber)
    {
    
        std::istringstream is(maybeNumber);
        float number = 0.0f;
        if (is >> number)
        {
            dat[i] = number;
            i++;
        }    
    }
    

    (You don't want to use eof. Everyone thinks they want to use eof, but it's almost always not what they need. See this question for details.)