• [c++]Problem with conditions
    5 replies, posted
[CODE] Console::Write("Please enter your state. WA or OR: "); Console::ReadString(state, sizeof(state)); while ((strcmp(state, "OR") != 0) || (strcmp(state, "WA") != 0)) { Console::Write("The software is intended for Washington and Oregon customer only. Please enter WA for Washington or OR for Oregon: "); Console::ReadString(state, sizeof(state)); if (strcmp(state, "OR") == 0 || strcmp(state, "WA") == 0) break; }[/CODE] User supposed to enter WA or OR only. The program has to loop until WA or OR is entered. If I enter whatever for first request then program goes to while loop. This is good. But then if I enter WA or OR (inside the while loop now) it keeps looping. If I enter OR or WA for first request then program goes into while loop. This is bad. I tried adding parentheses and even a break inside the loop. No luck. Edit: We are required to use cstring instead of string. Console is just a class that i made.
while ((strcmp(state, "OR") != 0) || (strcmp(state, "WA") != 0)) translates to: Loop if it isn't OR or if it isn't WA.
[QUOTE=DarkCybo7;39177227]while ((strcmp(state, "OR") != 0) || (strcmp(state, "WA") != 0)) translates to: Loop if it isn't OR or if it isn't WA.[/QUOTE] Yup and the following code translates to: if state is OR or WA [CODE]if (strcmp(state, "OR") == 0 || strcmp(state, "WA") == 0)[/CODE] So in theory it should work, yet loop is never exited; [IMG]http://i.imgur.com/MFHbE.png[/IMG] [CODE] while ((strcmp("OR", state) != 0) || (strcmp("WA", state) != 0)) { Console::Write("The software is intended for Washington and Oregon customer only. Please enter WA for Washington or OR for Oregon: "); Console::ReadString(state, sizeof(state)); if ( (strcmp("OR", state) == 0) || (strcmp("WA", state) == 0) ) { break; } }[/CODE] [B][U]SOLVED.[/U][/B] I forgot that with cstring last character is '\0' so I had to change state size from 2 to 3 But of course instead of doing that I changed the size to "size +1" in my Console::ReadString function.
You said it will loop if you enter WA or OR first. My point is that if you enter WA, one of the conditions will be true, and if you enter OR, the other condition will always be true, and if you enter neither WA or OR, then both conditions will be true. So the loop will ALWAYS occur.
SOLVED. I forgot that with cstring last character is '\0' so I had to change state size from 2 to 3 But of course instead of doing that I changed the size to "size +1" in my Console::ReadString function.
[QUOTE=P1X3;39177301]SOLVED. I forgot that with cstring last character is '\0' so I had to change state size from 2 to 3 But of course instead of doing that I changed the size to "size +1" in my Console::ReadString function.[/QUOTE] No, you should increase the size of "state" from 2 to 3. For statically allocated arrays, sizeof will be array_size*number_of_elements.
Sorry, you need to Log In to post a reply to this thread.