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)
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:
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.
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;
}