【发布时间】:2015-05-11 11:38:48
【问题描述】:
我是 C++ 新手,我正在做一个基本的 C++ 项目。
我有一些文本行(其中包含空格),我想让程序从标准输入中接受,然后在遇到(模拟的)EOF 时停止,因为 Ctrl + D.
我已经查找并尝试了here 和here 给出的解决方案。它们起作用,即当我点击 Ctrl + D 后,while 循环中的代码停止执行,但由于某种原因,以下代码行没有被执行。
我尝试了各种方法来做到这一点,但我一直遇到同样的问题。
string line;
int i = 0;
while (true) {
if (getline(cin, line)) {
A[i] = line;
cout << A[i] << endl; //executes as expected
i++;
} else {
break;
}
}
cout << "exited" << endl; //not executed even after ctrl+d
这是我尝试的另一种方法:
string line;
int i = 0;
while (getline(cin, line)){
//cin.ignore();
A[i] = line;
cout << A[i] << endl; //executes as expected
i++;
}
cout << "exited" << endl; //still not executed
示例输入:
DUCHESS 26
MARIE 8
BERLIOZ 8
TOULOUSE 7
THOMAS 28
PS:我在 Ubuntu 上使用 Eclipse CDT。
提前感谢您提供的任何帮助。
【问题讨论】:
-
此问题发布于 2015 年 5 月,Eclipse Oxygen Release (4.7.0) Build id: 20170620-1800 中仍然存在错误。 :(