假设我写了:
...
char c;
while(condition){
cin>>c;
//do stuff
...
}
...
如果在cin中输入了
2
字符,则下一个cin将采用第二个字符而我不给出任何字符。所以,我尝试了这个:...
char c;
while(condition){
cin<<c
//do stuff
...
cin.ignore("999 \n");
}
...
在这种情况下,程序将仅保留第一个输入即可工作,但是是否可以检查用户在cin中输入了多少个字符以打印适当的消息?
例如,如果输入为
ab
,它将打印类似“请仅输入一个字符”的内容。 最佳答案
阅读std::string
并验证:
while(condition){
std::string s;
std::cin >> s;
if (s.length() != 1){
// oops - make sure s[0] is not taken
}
c = s[0];
// do stuff
}
关于c++ - 确定cin中给出了多少个字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49316565/