-1

嘿,我试图验证一个字符以将其限制为接受男性或女性的 m 或 f。但即使按下 m 或 f 并继续循环问题,它也不会通过 while 条件。

任何人都可以帮我解决这个问题。提前致谢。这是我的代码:

char Validator :: getChar(string q)
{
    char input;
    do
    {
        cout << q.c_str() << endl;
        cin >> input;
    }
    while(!isalpha(input) && "M"||"F"||"m"||"f");
    return input;
}
4

3 回答 3

2

您的"M"||"F"||"m"||"f"代码部分没有按照您的想法执行。它所做的是检查这些字符串常量的地址。由于它们都是非 NULL,因此该表达式仅返回 true,因此您的条件本质上变为:while(!isalpha(input) && true)while(!isalpha(input)).

试试这个:

char Validator::getChar(const string &q)
{
    char input = 0;

    do
    {
        cout << q << endl;
        cin >> input;
    }
    while((input != 'M') && (input != 'F') && (input != 'm') && (input != 'f'));

    return input;
}
于 2012-11-28T22:16:43.170 回答
1

只是为了终止条件的另一种方法:

char Validator::getChar(const string &q)
{
    const std::set<char> valid_chars { 'M', 'm', 'F', 'f' };
    char input = 0;

    do
    {
        cout << q << endl;
        cin >> input;
    }
    while (!valid_chars.count(q));

    return input;
}
于 2012-11-28T22:29:08.967 回答
1

中的表达while并不意味着你认为它做了什么。首先,!不适用于整个表达式,其次,“平等”不是一个隐含的测试。你需要写出你的意思。

要测试是否相等,请使用==or!=运算符。您必须在要测试的每个值上使用运算符;运算符不会像普通英语那样“分布”在值列表上。像这样写下你的条件:

while (input != 'M' && input != 'F' && input != 'm' && input != 'f');

你可以看到isalpha调用是不必要的;如果input不等于任何列出的值,那么它是否是字母字符并不重要。

另一种写法是这样的:

while (!(input == 'M' || input == 'F' || input == 'm' || input == 'f'));

请注意,我在内部术语周围有另一组括号,以便!运算符适用于整个表达式,而不仅仅是第一个术语。

于 2012-11-28T22:14:14.527 回答