简体   繁体   中英

C++ do-while loop

guys! I was writing a program in C++ to demonstrate the 'do-while' loop. The program simply echoes whatever the user types as long as it is not 'goodbye.' So if the user enters 'hey' the program echoes 'hey' and if the user enters 'goodbye' the program stops. This is the code:

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{ 
string wordString;

do
{
    cout << "\nEnter a word: ";
    getline(cin, wordString);
    cout << "\nYou entered: " << wordString<<"\n";
} while ((wordString!="goodbye")||(wordString!="Goodbye"));

return 0;
} 

What I wanted to do was to make the program stop when the user enters the words 'goodbye' or 'Goodbye.' And so I added || to check that but it doesn't work and the loop statements simply continue to execute. But when I put && instead of || it worked properly and the program stopped whenever 'goodbye' or 'Goodbye' was entered.

So my question is this: Why does && work and || doesn't?

Using || does not stop the program because it is the OR operator it means that it will be true when anyone of the statement is true so if anyone it is true then it will execute on the other hand in AND( && ) operator it means both of the statement have to be true in order to execute.

You have to use logical and && not or || because in you want to break the loop if only wordstring not equal ro "goodbye" AND not equal to "GOODBYE":

while( wordString != "goodbye") && (wordString != "Goodbye");

Or you can use OR || this way:

while(wordString == "goodbye" || wordString == "Goodbye");

As you can see with OR if wordString contains Either "goodbye" or "GOODBYE" then break. Logical OR returns true if either of the operands is non-zeror and false if both are zeroed. Logical AND "&&" returns true if only and if the two operands are non-zero otherwise false (0).

What I can see if the user inputs "Goodbye" ; The first character in Capital or any mixture of small and capital letters then you'll program will looks ridiculous; Because it doesn't break.

The workaround is you can convert the input text to either to all capital or small letters then check only for one value:

std::string wordString = "GoodBye";
for(int i(0); i < wordString.length(); i++)
    wordString[i] = to_upper(wordString[i]);

// wordString = "GOODBYE"

 // ....
 while(wordString != "GOODBYE");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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