当用户输入多个带有字符变量的字符时出现错误

Bug when user input more than a character with char variable

本文关键字:字符 错误 字符变量 输入 用户      更新时间:2023-10-16

我正在制作简单的程序,如果用户输入"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;
}