我正在利用 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;
}
Run Code Online (Sandbox Code Playgroud)
我读了basic_istream::sentry和std::cin::get。
我选择使用std::getlinewhile 循环执行两次,因为流不为空。
std::string line; std::getline(std::cin, line);
Run Code Online (Sandbox Code Playgroud)
正如我上面发布的参考资料在其中一个答案中所述,std::cin用于读取字符并std::cin::get用于删除换行符\n。
char x; std::cin >> x; std::cin.get();
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么要在流上std::cin留下换行符\n?
因为这是它的默认行为,但您可以更改它。尝试这个:
#include<iostream>
using namespace std;
int main(int argc, char * argv[]) {
char y, z;
cin >> y;
cin >> noskipws >> z;
cout << "y->" << y << "<-" << endl;
cout << "z->" << z << "<-" << endl;
}
Run Code Online (Sandbox Code Playgroud)
向其提供一个由单个字符和换行符(“a\n”)组成的文件,输出为:
y->a<-
z->
<-
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15111 次 |
| 最近记录: |