开发者

else if string compare problem

开发者 https://www.devze.com 2023-01-07 00:08 出处:网络
I have the following if statements, two of which don\'t seem to work. I don\'t get why it works when I try to compare it to a single character \"y\" or \"n\" but not when I try to compare it to two ch

I have the following if statements, two of which don't seem to work. I don't get why it works when I try to compare it to a single character "y" or "n" but not when I try to compare it to two characters in one else if statement.

The last question I have is if there's a better cleaner way to write this or if this acceptable for a simple prompt check?

getline(cin,somestr);

if(so开发者_Python百科mestr.empty()){
//do this
}
else if (somestr == "y" || "Y"){
//do something else
}
else if (somestr == "n" || "N"){
//do something else
}
else{}


You would do it like this:

else if(somestr == "y" || somestr == "Y")


if (somestr == "y" || "Y"){

Keep in mind, in C++ 0 is false and everything else is true. Since "Y" is not zero, it's true. So what you've really written is: if (something || true). Which is always true.


Unfortunately, the language doesn't give you an easy way to check a variable against a set of possibilities. You have to do each test individually or use a switch statement. So, either of the following code samples would be a valid solution for your problem:

else if (somestr == 'y' || somestr == 'Y'){
//do something else
}
else if (somestr == 'n' || somestr == 'N'){
//do something else
}


switch (somestr) {
    case 'y':
    case 'Y':
        // do something
        break;

    case 'n':
    case 'N':
        // do something
        break;

    default:
        break;
}

Alternatively, you can clean up your code a bit by reducing some of your logic (assuming somestr is a char):

// Convert to uppercase first and only one comparison is needed
else if (toupper(somestr) == 'Y'){
//do something else
}
else if (toupper(somestr) == 'N'){
//do something else
}


I would do something like

else if(someFunctionThatConvertsToUpper(somestr) == "Y")


Anther option, especially if you're only expecting characters - it looks like y or n for yes or no - is to read in a char, not a string, and use a switch statement.

char somechar;
cin.get(somechar);

switch(somechar){
  case 'y' : case 'Y':
    //do something
  break;
  case 'n' : case 'N':
    // do something else
    // break;
  default:
    // do something else
}


You should write two comparisons

somestr == "n" ||  somestr=="N"


First of all, you need to fix this:

(somestr == "y" || "Y")  to (somestr == "y" || somestr == "Y")

and

(somestr == "n" || "N")  to (somestr == "n" || somestr == "N")

Otherwise, these expressions always evaluate to true because any string by itself such as "y" evaluates to true along with anything else other than 0.

Secondly, you may want to ask for input again if it is not "y", "Y", "n" or "N". You could use a do-while loop to accomplish this.

0

精彩评论

暂无评论...
验证码 换一张
取 消