【发布时间】:2021-08-19 15:20:52
【问题描述】:
请考虑下面的 C++ 代码:
#include <string>
#include <iostream>
using namespace std;
void fun1() {
cout << "Calling fun1" << endl;
}
void fun2() {
cout << "Calling fun2" << endl;
}
int main() {
string s1, s2;
while (cin >> s1) {
fun1();
while (cin >> s2) {
fun2();
}
}
return 0;
}
代码中有两个嵌套的while循环,在外层while循环中,使用cin输入值并调用fun1;然后进入内部while循环,使用cin输入一个值并调用fun2。但是当我想通过ctrl + d 终止内部while 循环时,我发现外部while 循环也终止了。我知道我可以使用下面的代码 sn -p 来解决这个问题,但是我想知道为什么会出现上述情况?提前致谢。
while (cin >> s1) {
if (s1 == "end1")
break;
fun1();
while (cin >> s2) {
if (s2 == "end2")
break;
fun2();
}
}
【问题讨论】:
-
使用
ctrl-D(或Windows 上的ctrl-Z)关闭标准输入完全在您的程序之外——这不是编译器放入可执行文件的代码的结果,而是操作系统做它的事情的结果。这实际上是关于您的计算机如何工作的问题,而不是关于编程的问题。
标签: c++ while-loop cin