Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ DO loop being strange

Tags:

c++

loops

First of all, here is my code:

string text;
do {
   cout << "Enter text: ";
   ws(cin);
   getline(cin, text);
} while (!text.empty());
// do stuff

What I want my code to do ?
- Check if the user input is empty ;
if the userinput = empty, loop to the beginning and he has to enter new text.
If userinput != empty, get out of the loop and continue the program.

What is my code doing ?
- When I enter a text, the loop start from the beginning and I have to retype a text.
- When I do not enter anything and just type enter, my program is indefinitely waiting and I need to Ctrl+C to exit.

like image 984
Amat Erasu Avatar asked Nov 18 '25 07:11

Amat Erasu


1 Answers

It's not a repeat-until, but a do-while loop, use:

string text;
do {
   cout << "Enter text: ";
   ws(cin);
   getline(cin, text);
} while (text.empty());
//      ^^

Basically if the condition is true then it loops again, otherwise it breaks the loop. In your case it's looping if the string is not empty, and breaking the loop if the string is empty.

like image 194
Shoe Avatar answered Nov 20 '25 19:11

Shoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!