user3247278
user3247278

Reputation: 179

Reading in input file with strings and doubles separated by commas and multiple lines. C++

How can I read an input file that has strings and doubles separated by commas with multiple lines. I want to keep the strings in a multidimensional array like char Teams[5][40] For examples the file is something like:

Team1,0.80,0.30
Team1,0.30,0.20
Team1,0.20,0.70
Team1,0.70,0.80
Team1,0.90,0.20

I was thinking about using strtok but I'm not sure how to iterate throughout everything and all the lines while making keeping the doubles assigned to their string on each line. Any ideas? Thanks!

Upvotes: 1

Views: 1453

Answers (1)

Ali Alavi
Ali Alavi

Reputation: 2467

You can use the third argument of getline to set a delimiter other than '\n'. You will use an array version of the following code:

string temp;
while(std::getline(file,line))
{
    std::getline(ss,temp,','); // read first value into temp and move the stream to next value

    string team(temp); 
    int a,b,c;

    ss >> a; // read the stream into a
    std::getline(ss,temp,',');  // move to next value
    ss >> b;  // read into b
    std::getline(ss,temp,','); // move to next value
    ss >> c; // read into c
}

Upvotes: 2

Related Questions