在c++中,不等于(!=)运算符不能正确使用字符

Not equal (!=) operator not working with correctly char in c++

本文关键字:不能 运算符 字符 c++ 不等于      更新时间:2023-10-16

此代码工作不正常,请帮助我。即使我输入了正确的字符,它也一直要求"输入正确的数字"。它并没有评估这种情况。

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
    char ch = '0';
    A:
    cout << "enter a Character" << endl;
    cin >> ch;
    if ((ch != 'X')||(ch != 'x'))
    {
        cout << "Please Enter Right Number" << endl;
        goto A;
    }
    return 0;
}

使用

    if ((ch != 'X') && (ch != 'x'))

而不是

  if ((ch != 'X')||(ch != 'x'))

也可以使用循环而不是使用goto

 cout << "enter a Character" << endl;
 cin >> ch;
 while(ch!='X' && ch!='x')
 {
      cout << "Please Enter Right Number" << endl;
      cout << "enter a Character" << endl;
      cin>>ch;
 }

(ch != 'X')||(ch != 'x')始终是true,您的意思可能是&&而不是||