C++ 告诉 cin 在换行符处停止阅读
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9673708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
tell cin to stop reading at newline
提问by Mark
Suppose I want to read line a of integers from input like this:
假设我想从输入中读取整数 a 行,如下所示:
1 2 3 4 5\n
I want cin to stop at '\n' character but cin doesn't seem to recognize it.
我希望 cin 停在 '\n' 字符处,但 cin 似乎无法识别它。
Below is what I used.
下面是我用的。
vector<int> getclause() {
char c;
vector<int> cl;
while ( cin >> c && c!='\n') {
cl.push_back(c);
cin>>c;
}
return cl;
}
How should I modify this so that cin stop when it see the '\n' character?
我应该如何修改它,以便 cin 在看到 '\n' 字符时停止?
回答by mfontanini
Use getline and istringstream:
使用 getline 和 istringstream:
#include <sstream>
/*....*/
vector<int> getclause() {
char c;
vector<int> cl;
std::string line;
std::getline(cin, line);
std::istringstream iss(line);
while ( iss >> c) {
cl.push_back(c);
}
return cl;
}
回答by Geoffroy
You can use the getlinemethod to first get the line, then use istringstreamto get formatted input from the line.
您可以使用getline方法首先获取该行,然后使用istringstream从该行获取格式化的输入。
回答by piokuc
Use std::getline, this will do the trick
使用 std::getline,这会解决问题