当用户输入多个带有字符变量的字符时出现错误
Bug when user input more than a character with char variable
我正在制作简单的程序,如果用户输入"z",则显示"True",如果用户输入其他任何内容,则显示"False"。但是,问题是当用户输入多个字符时,例如当用户输入"zz"时,输出是
True
Input : True
当用户输入诸如"zs"之类的应该错误时,输出是
True
Input : Wrong
这是我的代码
#include <iostream>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while(true){
cout << "Input : ";
cin >> input;
if(input=='z'){
cout << "True" << endl;
} else {
cout << "Wrong" << endl;
}
}
return 0;
}
我想知道是否有办法在不将变量类型更改为字符串的情况下防止这种情况?
我在Windows 10 x64上使用CodeBlocks 16.04(MinGW)和GNU GCC编译器
你不能通过读取单个字符来做到这一点。关键是,如果用户输入例如z z,他实际上确实输入了这两个字符,而这些是您在从cin
读取时获得的字符。
只需按照建议读取std::string
,并仅检查字符串的第一个字符。这就像你正在做的事情一样简单。
所以你可能想要这个:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
if (input.length() > 0 && input[0] == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
}
return 0;
}
绝对有可能,您只需检查第一个字符并确保它是唯一输入的字符,然后刷新缓冲区以摆脱字符串的其余部分。
法典:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
//Check if the input is z and there is only 1 character inputted
if (cin.rdbuf()->in_avail() == 1 && input == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
//Flush the buffer
cin.clear();
cin.ignore(INT_MAX, 'n');
}
return 0;
}
相关文章:
- 我的字符计数代码计算错误.为什么
- 错误:字符数组的初始值设定项太多
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- C++ 字符错误
- CppLint铸造字符*错误
- R data.table 和 STRING_ELT() 错误:如何修复"字符向量"与"字符"错误?
- C URL用UTF8字符错误解码
- C++:如何在 do while 循环中解决字符错误
- 遍历字符* 错误没有从字符* 转换为 int
- Arduino SIM800L:将字符串转换为字符* 错误
- Qt 中的常量字符* 错误行为
- 返回c++中的字符错误数组
- C++:队列中的第一个字符错误
- c++ SFML 按键字符错误
- C++字符*错误,程序崩溃
- 输出字符串/字符错误(c++)
- 将输入字符串转换为字符* <错误 Ptr>
- 井字棋数组字符错误
- c++读取字符串字符错误
- CouchDB UTF-8字符错误