Search code examples
c++readfile

C++ Read file line by line then split each line using the delimiter


I want to read a txt file line by line and after reading each line, I want to split the line according to the tab "\t" and add each part to an element in a struct.

my struct is 1*char and 2*int

struct myStruct
{
    char chr;
    int v1;
    int v2;
}

where chr can contain more than one character.

A line should be something like:

randomstring TAB number TAB number NL

Solution

  • Try:
    Note: if chr can contain more than 1 character then use a string to represent it.

    std::ifstream file("plop");
    std::string   line;
    
    while(std::getline(file, line))
    {
        std::stringstream   linestream(line);
        std::string         data;
        int                 val1;
        int                 val2;
    
        // If you have truly tab delimited data use getline() with third parameter.
        // If your data is just white space separated data
        // then the operator >> will do (it reads a space separated word into a string).
        std::getline(linestream, data, '\t');  // read up-to the first tab (discard tab).
    
        // Read the integers using the operator >>
        linestream >> val1 >> val2;
    }