我正在编写一个接受字符串变量的错误检查函数,我需要它成为“ Y”,“ N”,“ y”或“ n”之一。我的问题是,字符串变量始终设置为“ y”,这表明无论变量接收什么输入,if语句都不会超出第一个条件。如果有明显的错误,例如我在使用'||'运算符,如果有人可以告诉我,将对我有很大帮助。
if (string == "y" || "Y") { //If 'yes'...
string = "y"; //Standardise input for later use
return 1; //Error check successfully passed
}
else if (string == "n" || "N") { //If 'no'...
string = "n"; //Standardise input for later use
return 1; //Error check successfully passed
}
else { //If erroeneous input...
return 0; //Error check not passed
}
string == "y" || "Y"
并没有做您想做的:将string
与"y"
进行比较,然后将其结果与"Y"
进行或运算。由于"Y"' is non-zero, it always evaluates to
true`。
正确的代码是:
string == "y" || string == "Y"
也可以将“ string”转换为char“ c”,并使用tolower(c)函数,在相同条件下可以将“ y”和“ n”进行比较,因为返回值在两种情况。
还有boost :: to_lower(data)选项;