参考Why is the Console Closing after I've included cin.get()?的std :: CIN ::为什么换行仍然
我利用std::cin.get()
#include<iostream>
char decision = ' ';
bool wrong = true;
while (wrong) {
std::cout << "\n(I)nteractive or (B)atch Session?: ";
if(std::cin) {
decision = std::cin.get();
if(std::cin.eof())
throw CustomException("Error occurred while reading input\n");
} else {
throw CustomException("Error occurred while reading input\n");
}
decision = std::tolower(decision);
if (decision != 'i' && decision != 'b')
std::cout << "\nPlease enter an 'I' or 'B'\n";
else
wrong = false;
}
我读basic_istream::sentry和std::cin::get。
我选择使用std::getline
作为while循环执行两次,因为流不是空的。
std::string line; std::getline(std::cin, line);
作为参考我张贴上述状态的答案中的一个内,std::cin
被用于读取一个字符和std::cin::get
来除去换行符\n
。
char x; std::cin >> x; std::cin.get();
我的问题是,为什么std::cin
留在流换行符\n
?
为什么阅读比它更多? – chris 2013-04-09 14:50:54
在C++ I/O是抽象的。没有控制台的概念,所有I/O都通过相同的底层代码。如果您正在读取一个文件,您不希望I/O操作是基于行的,那么您会希望I/O操作读取他们所需的内容,而不再需要它。所以控制台I/O也是如此。 – john 2013-04-09 14:54:37
[为什么cin命令在缓冲区中留下一个'\ n']可能重复(http://stackoverflow.com/questions/28109679/why-does-cin-command-leaves-an-in-the-buffer ) – 2017-03-17 18:59:02