从cin读取getline到stringstream(C ++) [英] Reading getline from cin into a stringstream (C++)
问题描述
所以我试图从标准输入中读取这样的输入(使用 cin
):
So I'm trying to read input like this from the standard input (using cin
):
亚当英语85
查理数学76
埃里卡历史82
理查德科学90
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;
我遇到的错误是XCode告诉我没有匹配的函数调用 getline
这让我感到困惑。我已经包含了 string
库,所以我猜该错误与使用 getline
进行读取有关 cin
到 stringstream
?
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.
推荐答案
您快到了,错误很可能是 1 由于您尝试使用第二个参数 stringstream
调用 getline
造成的,只需稍加修改并将数据存储在首先在字符串
中使用 std :: cin
,然后使用它来初始化 stringstream
,您可以从中提取输入:
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。假设您已经包括:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
这篇关于从cin读取getline到stringstream(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!