8

I'm new to C++. I'm sorry if this question is duplicated but I just can't find similar question.

very basic code:

string s;
while (cin >> s)
    cout << s << endl;

I expect the loop stop when I press the return in my keyboard. But it never stop....

I know that cin will return false when it encounters invalid input, for example if we use

int i;
while (cin >> i)
    cout << i << endl;

then the loop ends when we enter a non-integer.

But in case of string, how can we stop that loop?

Ziqi Liu
  • 2,931
  • 5
  • 31
  • 64
  • Are you trying to read a line? If that's the case then you should do: `std::getline(std::cin, s);` – DimChtz Jun 23 '18 at 09:59
  • 2
    Possible duplicate of [How to signify no more input for string ss in the loop while (cin >> ss)](https://stackoverflow.com/questions/5360129/how-to-signify-no-more-input-for-string-ss-in-the-loop-while-cin-ss) – xskxzr Jun 23 '18 at 10:03

2 Answers2

12

while (cin >> s) { ... } will loop as long as the input is valid. It will exit the loop when the attempted input fails.

There are two possible reasons for failure:

  1. Invalid input
  2. End of file

Assuming that the input itself is valid, in order to terminate the loop the input stream has to reach the end.

When the input is actually a file, recognizing the end is easy: when it runs out of characters it's at the end of the file. When it's the console, it's not so easy: you have to do something artificial to indicate the end of the input.

Do that, you have to tell the terminal application (which controls the console) that there is no more input, and the terminal application, in turn, will tell your program that it's at the end of the input.

The way you do that depends on the terminal application, which is typically part of the operating system.

  • On Windows, ctrl-Z tells the terminal application that you're at the end of your input.
  • On Unix systems, it's ctrl-D.
JeJo
  • 30,635
  • 6
  • 49
  • 88
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
3

You can signal EOF via CTRL-D or CTRL-Z.

Or, you can check for a particular string to break the loop, like below:

string s;
while (cin >> s)
  {
     if(s == "end")
          break;
     cout << s << endl;
  }
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mr. Roshan
  • 1,777
  • 13
  • 33