Reading getline from cin into a stringstream (C++)

user5482356 picture user5482356 · Mar 13, 2016 · Viewed 42.1k times · Source

So I'm trying to read input like this from the standard input (using cin):

Adam English 85
Charlie Math 76
Erica History 82
Richard Science 90

My goal is to eventually store each data piece in its own cell in a data structure I have created, so basically I want to parse the input so each piece of data is individual. Since each row of input is inputted by the user one at a time, each time I get an entire row of input that I need to parse. Currently I am trying something like this:

stringstream ss;
getline(cin, ss);

string name;
string course;
string grade;
ss >> name >> course >> grade;

The error I am having is that XCode is telling me there's no matching function call to getline which is confusing me. I have included the string library, so I'm guessing the error has to do with using getline to read in from cin to a stringstream? Any help here would be appreciated.

Answer

Ziezi picture Ziezi · Mar 13, 2016

You are almost there, the error is most probably1 caused because you are trying to call getline with second parameter stringstream, just make a slight modification and store the data within the std::cin in a string first and then used it to initialize a stringstream, from which you can extract the input:

// read input
string input;
getline(cin, input);

// initialize string stream
stringstream ss(input);

// extract input
string name;
string course;
string grade;

ss >> name >> course >> grade;

1. Assuming you have included:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;