为什么我的C++代码仍在运行?我看不出理由
这可能是一个非常简单的问题,但我无法弄清楚。我有这段代码,非常基本的代码,甚至没有条件结构。但即使输入后,它也不会停止运行。我一定是在清理缓冲区时做错了什么。
#include <iostream>
#include <string>
#include <limits>
int main()
{
std::string sentence{};
std::cout << "Enter a sentencen";
std::cin >> sentence;
std::cout << "Input sentence : " << sentence << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
return 0;
}
顺便说一句,我正在使用以下命令进行编译:
g++ main.cpp -std=c++14 -o program
谢谢你的帮助。
回答
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
意味着读取和丢弃输入直到到达文件结尾。这意味着在你给出第一行输入之后,程序接收并打印回给你,这个函数将继续消耗输入而不用它做任何事情,因为这正是你告诉它要做的。如果您通过终端运行程序,您应该能够用一些组合键来表示文件结束,这在 Mac 和 Linux 上通常是 Ctrl-D,在 Windows 上通常是 Ctrl-Z。然后对 的调用ignore将返回到main,然后return 0结束程序。
当然,程序没有理由有这种行为。只需阅读第一行,打印它,然后退出。
int main() {
std::string sentence;
std::cout << "Enter a sentencen";
std::cin >> sentence;
std::cout << "Input sentence: " << sentence << "n";
return 0;
}
您不需要调用clear或ignore。