在 C++ 中从标准输入读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10464344/
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
reading from stdin in c++
提问by krisdigitx
I am trying to read from stdin using C++, using this code
我正在尝试使用 C++ 从标准输入读取,使用此代码
#include <iostream>
using namespace std;
int main() {
while(cin) {
getline(cin, input_line);
cout << input_line << endl;
};
return 0;
}
when i compile, i get this error..
当我编译时,我收到此错误..
[root@proxy-001 krisdigitx]# g++ -o capture -O3 capture.cpp
capture.cpp: In function aint main()a:
capture.cpp:6: error: ainput_linea was not declared in this scope
Any ideas whats missing?
任何想法缺少什么?
回答by loganfsmyth
You have not defined the variable input_line
.
您尚未定义变量input_line
。
Add this:
添加这个:
string input_line;
And add this include.
并添加这个包括。
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
这是完整的示例。我还在 while 循环之后删除了分号,您应该getline
在 while 内正确检测流的结尾。
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}