【发布时间】:2013-04-01 01:28:39
【问题描述】:
参考Why is the Console Closing after I've included cin.get()?
我正在使用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?
【问题讨论】:
-
为什么要多读书?
-
在 C++ 中,I/O 是抽象的。没有控制台的概念,所有 I/O 都通过相同的底层代码。如果您正在读取文件,您不会期望 I/O 操作是基于行的,您会期望 I/O 操作读取它们需要的内容,而不是更多。所以控制台 I/O 也是如此。