Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当用户使用char变量输入多个字符时出现错误_C++_Codeblocks - Fatal编程技术网

C++ 当用户使用char变量输入多个字符时出现错误

C++ 当用户使用char变量输入多个字符时出现错误,c++,codeblocks,C++,Codeblocks,我正在制作一个简单的程序,如果用户输入“z”,则显示True,如果用户输入其他内容,则显示False。 但是,问题是当用户输入的字符超过一个字符时,例如当用户输入'zz'时,输出是无效的 True Input : True True Input : Wrong 当用户输入的“zs”应该是错误的时,输出是错误的 True Input : True True Input : Wrong 这是我的密码 #include <iostream> using namespace std

我正在制作一个简单的程序,如果用户输入“z”,则显示True,如果用户输入其他内容,则显示False。 但是,问题是当用户输入的字符超过一个字符时,例如当用户输入'zz'时,输出是无效的

True
Input : True
True
Input : Wrong
当用户输入的“zs”应该是错误的时,输出是错误的

True
Input : True
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上,我将代码块16.04 MinGW与GNU GCC编译器一起使用

您不能通过读取单个字符来实现这一点。关键是,如果用户输入例如zz,他实际上输入了这两个字符,这些是您从cin读取时得到的字符

只需按照建议读取一个std::字符串,并只检查字符串的第一个字符。这和你所做的一样简单

所以你可能想要这个:

#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;
}

当然,您只需检查第一个字符并确保它是输入的唯一字符,然后刷新缓冲区以清除字符串的其余部分

代码:


读一个std::string而不是单个字符怎么样?@user0042我已经试过了,并且成功了,但是由于我的目标是输入和检查单个字符,如果可能的话,我希望使用char。您提供的输出与示例产生的结果不匹配。如果您读一个字符,您将读取输入的第一个字符。除非您也尝试读取字符,否则您不可能知道后面是否还有更多字符。您希望您的程序如何知道它何时读取了用户将提供的所有输入?如果您的答案是,我想读入一行输入,然后检查它是否有效,那么为什么不编写这样做的代码呢?这在zz或zs等场景中仍然是正确的,请尝试将input.length>0更改为input.length==1