Search code examples
c++integerfstreamsstream

C++ read only integers in an fstream


How do I read in a file and ignore nonintegers? I have the part down where I remove the ',' from the file, but also need to remove the first word as well.

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

above is all the STL I am using.

string line, data;

int num;

bool IN = false;

ifstream file;

file.open(filename);
if (!file)
{
    cout << "File is not loading" << endl;
    return;
}
while (getline(file, line))
{
    stringstream ss(line);
    while (getline(ss, data, ','))
    {
        if (!stoi(data))
        {
            break;
        }
        else
        {
            num = stoi(data);
            if (IN == false)
            {
                //h(num);
                //IN = true;
            }
        }
    }
}

The file I am trying to read from is

3
Andrew A,0,1
Jason B,2,1
Joseph C,3,0

Basically, I am able to just completely ignore the names. I just need the numbers


Solution

  • You already know how to read line-by-line, and break up a line into words based on commas. The only problem I see with your code is you are misusing stoi(). It throws an exception on failure, which you are not catching, eg:

    while (getline(ss, data, ','))
    {
        try {
            num = stoi(data);
        }
        catch (const exception&) {
            continue; // or break; your choice
        }
        // use num as needed...
    }
    

    On the other hand, if you know the 1st word of each line is always a non-integer, then just ignore it unconditionally, eg:

    while (getline(file, line))
    {
        istringstream ss(line);
    
        getline(ss, data, ',');
        // or:
        // ss.ignore(numeric_limits<streamsize>::max(), ',');
    
        while (getline(ss, data, ','))
        {
           num = stoi(data);
           // use num as needed...
        }
    }