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

前端 未结 4 1700
自闭症患者
自闭症患者 2020-12-15 08:52

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

Adam English 85
Charlie Math 76
Erica His

4条回答
  •  春和景丽
    2020-12-15 09:20

    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  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.

提交回复
热议问题