1
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++?

anastaciu
  • 20,013
  • 7
  • 23
  • 43
  • 3
    Does this answer your question? [Parse (split) a string in C++ using string delimiter (standard C++)](https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) [that one](https://stackoverflow.com/a/37454181/4165552) is my favorite solution. – pptaszni Apr 07 '21 at 13:30
  • If it's the presence of tabs that is holding you back, be aware that tabs are considered as [whitespace](https://en.cppreference.com/w/cpp/string/byte/isspace) for the purposes of [stream extraction](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt). – acraig5075 Apr 07 '21 at 13:50

1 Answers1

2

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.

anastaciu
  • 20,013
  • 7
  • 23
  • 43