Split a string of tab separated integers and store them in a vector

Viewed 326
ifstream infile;
infile.open("graph.txt");
string line;
while (getline(infile, line))
{
       //TODO
}
infile.close();

I am taking input line by line from the file and storing each line in the string "line".

Each line contains integers separated by tabs. I want to get these integers separated and store each integer inside a vector. But I don't know how to proceed. Is there something like a split function for strings in C++?

1 Answers

The duplicate has some solutions, I would, however, prefer to use a stringstream, something like:

#include <sstream>

//...

vector<int> v;

if (infile.is_open()) // make sure the file opening was successful
{
    while (getline(infile, line))
    {
        int temp;
        stringstream ss(line); // convert string into a stream
        while (ss >> temp)     // convert each word on the stream into an int
        {
            v.push_back(temp); // store it in the vector
        }
    }
}

As Ted Lyngmo stated this will store all the int values from the file in the vector v, assuming that the file in fact only has int values, for example, alphabetic characters or integers outside the range of what an int can take will not be parsed and will trigger a stream error state for that line only, continuing to parse in the next line.

Related