简体   繁体   English

(C ++)如何验证用户输入的char变量?

[英](C++) How to validate user input for char variables?

I'm having trouble comparing user input for a char variable. 我在比较用户输入的char变量时遇到问题。 I want to check if they answered Y or N to a question. 我想检查他们是否回答一个问题。 If they did not put a Y or NI want to give the user an error message and start the loop over. 如果他们没有输入Y或NI,则想给用户一条错误消息并开始循环。

Below is the test code I created as a template for the program I intend to use it for. 下面是我创建的测试代码,将其作为要使用的程序的模板。 The program loops no matter what input the user gives. 无论用户提供什么输入,程序都会循环执行。 Also, if the user inputs 'n' characters, they will receive 'n' "Failure!" 另外,如果用户输入“ n”个字符,他们将收到“ n”个“ Failure!”。 messages along with the initial cout message each time. 消息以及初始cout消息。 If they input Y it happens as well except of course it says "Success!". 如果他们输入Y,那么它也会发生,当然会显示“成功!”。

I've looked around online but have yet to find anyone address this. 我在网上环顾四周,但尚未找到解决此问题的人。 Why does == work for equivalency checks but not != for chars (and strings as well for that matter)? 为什么==对于等效性检查有效,而!=对于字符(对于字符串也无效)无效?

#include<iostream>

using namespace std;

int main()
{
    char answer;

    do{
        cout <<"\nPlease type Y or N." << endl;
        cin >> answer;

        if ((answer == 'Y') || (answer == 'N'))
        {
            cout << "\nSuccess!" << endl;
        }
        else
        {
            cout << "\nFailure!" << endl;
        }
    }while ((answer != 'Y') || (answer != 'N'));

    return 0;
}

The problem lays in the following line: 问题在于以下几行:

while ((answer != 'Y') || (answer != 'N'));

Either one of these condition is always true and you are applying logic OR, thus you can never get out of this loop. 这些条件之一始终为true,并且您正在应用逻辑OR,因此您永远也无法摆脱这种循环。 You need to change this as follows: 您需要进行如下更改:

while (answer != 'Y' && answer != 'N') 

You misapplied Boole's logic: the negation of a disjunction is not a negation of the terms while keeping the disjunction. 您误用了Boole的逻辑:对析取词的否定并不等于在保留析取词时对术语的否定。 Instead, you need to negate the terms and use a conjunction. 相反,您需要取反这些术语并使用连词。

answer will always be not 'Y' or not 'N' answer将永远不是'Y''N'

((answer != 'Y') || (answer != 'N'))

you probably ment 你可能会提到

((answer != 'Y') && (answer != 'N'))

((answer != 'Y') || (answer != 'N'));

Means to loop until the user enters someting different than 'Y' OR different than 'N' , so it exist when the enters 'Y' or 'N' because, of course, they are different. 一直循环直到用户输入不同于'Y' 不同于'N' ,所以当输入'Y''N'时它就存在,因为它们当然是不同的。

You should loop as in the follwing chunk of code: 您应该像下面的代码块那样循环:

do {
  // code
} while ( answer == 'Y' && answer == 'N' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM