gpt4 book ai didi

c++ - 确定cin中给出了多少个字符?

转载 作者:行者123 更新时间:2023-11-27 22:40:37 27 4
gpt4 key购买 nike

假设我写了:

    ...
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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com