I am making a bowling program for school that stored scores in a text file with the format:
paul 10 9 1 8 1, ...etc
jerry 8 1 8 1 10 ...etc
...etc
I want to read the file into a stringstream
using getline()
so I can use each endl
as a marker for a new player's score (because the ammount of numbers on a line can be variable, if you get a spare or strike on round 10). I can then read the stringstream
using >>
to get each score and push it into a vector
individually.
However, when trying to use getline(fstream, stringstream)
, I get an error
no instance of overloaded function "getline" matches the argument list -- argument types are: (std::fstream, std::stringstream)
How can I make this work?
My code looks like this:
#include <iostream>
#include <vector>
#include <fstream>
#include <exception>
#include <string>
#include <sstream>
using namespace std;
//other parts of the program which probably don't matter for this error
vector <int> gameScore;
vector<string> playerName;
int i = 0;
int j = 0;
string name;
int score;
stringstream line;
while (in.good()){ //in is my fstream
playerName.push_back(name);
cout << playerName[i] << " ";
i ;
getline(in, line);
while (line >> score){
gameScore.push_back(score);
cout << gameScore[j] << " ";
j ;
}
}
CodePudding user response:
You can't use std::getline()
to read from a std::ifstream
directly into a std::stringstream
. You can only read into a std::string
, which you can then assign to the std::stringstream
, eg:
vector<int> gameScore;
vector<string> playerName;
string name, line;
int score;
while (getline(in, line)){
istringstream iss(line);
iss >> name;
playerName.push_back(name);
cout << name << " ";
while (iss >> score){
gameScore.push_back(score);
cout << score << " ";
}
}