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.
You cannot std::getline() a std::stringstream ; only a std::string . Read as a string, then use a stringstream to parse it.
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
Using std::getline() in C++ to split the input using delimiters. We can also use the delim argument to make the getline function split the input in terms of a delimiter character. By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!
Reading strings: get and getlineThe functions get and getline (with the three parameters) will read and store a c-style string. The parameters: First parameter (str) is the char array where the data will be stored.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With