Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ when will while(cin>>s) stop

Tags:

c++

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?

like image 215
Ziqi Liu Avatar asked Jun 23 '18 09:06

Ziqi Liu


People also ask

What does cin >> do?

cin in C++ The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs.

What does cin >> n mean in C++?

cin is the standard input stream. Usually the stuff someone types in with a keyboard. We can extract values of this stream, using the >> operator. So cin >> n; reads an integer. However, the result of (cin >> variable) is a reference to cin .

Why is while loop not ending?

The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop.

Can you put CIN in a while loop?

Well, you use cin inside a while loop when you need the user to enter a value that will be used after that, in the same loop. Everytime the loop runs, the user can chose something else. For example, calculating x*y.


1 Answers

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.
like image 146
Pete Becker Avatar answered Sep 17 '22 10:09

Pete Becker