3

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
Amat Erasu
  • 73
  • 5

1 Answers1

3

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.

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • Thanks for the answer, but that answer my second problem. Now I need the loop to restart when the userinput is empty -- for example user directly type "enter" – Amat Erasu Aug 25 '15 at 16:14
  • When text is empty and when he just type enter. – Amat Erasu Aug 25 '15 at 16:17
  • @AmatErasu That's what the above code is doing. It will restart the loop when the user input is empty. How else would the user send an empty text without pressing "enter" while having no input entered? – Shoe Aug 25 '15 at 16:17
  • I tried this code and when I type just enter on my keyboard, then program is not exiting nor reloading the loop. – Amat Erasu Aug 25 '15 at 16:35
  • If it doesn't exit, why do you think it's not reloading the loop? – Lightness Races in Orbit Aug 25 '15 at 17:24