Reading getline from cin into a stringstream (C++)
Solution 1
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;
Solution 2
You cannot std::getline()
a std::stringstream
; only a std::string
. Read as a string, then use a stringstream to parse it.
struct Student
{
string name;
string course;
unsigned grade;
};
vector <Student> students;
string s;
while (getline( cin, s ))
{
istringstream ss(s);
Student student;
if (ss >> student.name >> student.course >> student.grade)
students.emplace_back( student );
}
Hope this helps.
Solution 3
You can just use cin >> name >> course >> grade;
because >>
will read until whitespace anyway.
user313
Updated on August 31, 2020Comments
-
user313 over 3 years
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 90My 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 thestring
library, so I'm guessing the error has to do with usinggetline
to read in fromcin
to astringstream
? Any help here would be appreciated.-
Christian Hackl about 8 yearsDo you realise that your program will only work if name and course do not contain spaces? It will fail for "John Smith English" or "Adam Computer Science"...
-
-
Lightness Races in Orbit about 8 yearsAdding a line-by-line parsing layer is usually actually a good thing, though.
-
Manohar Reddy Poreddy over 7 yearsthis is best answer for me
-
Kasper over 4 years"will read until whitespace": it is not accurate. It'll read until the whitespace or tab or end of line
-
Yazan Alsalem over 3 years@Kasper tab and end-of-line characters are considered whitespace
-
Kasper over 3 yearsyou're right @YazanAlsalem. Specifically: cplusplus.com/reference/istream/istream/operator-free and cplusplus.com/reference/cctype/isspace for detailed info.