I used \"cin\" to read words from input stream, which like
int main( ){
string word;
while (cin >> word){
//do sth on the input word
It helps me to terminate loop by hitting ENTER.
int main() {
string word;
while(getline(cin,word) && s.compare("\0") != 0) {
//do sth on the input word
}
// perform some other operations
}
Take the input from a file. Then you will find that the while loop terminates when your program stops taking input.
Actually cin
stops taking input when it finds an EOF marker. Each input file ends with this EOF marker. When this EOF marker is encountered by operator>>
it modifies the value of internal flag eofbit
into false and consequently the while loop stops.
your program doesn't take in count white spaces. make difference between cin and getline...
here is an example with a trick: the program get input and prints output until you hit twice Enter to quit:
#include <iostream>
#include <string>
using namespace std;
int main(){
char c = '\0';
string word;
int nReturn = 0;
cout << "Hit Enter twice to quit\n\n";
while (cin.peek())
{
cin.get(c);
if(nReturn > 1)
break;
if('\n' == c)
nReturn++;
else
nReturn = 0;
word += c;
cout << word;
word = "";
}
cout << endl;
return 0;
}
As others already answer this question, I would like add this important point:
Since Ctrl-Z on Windows (and Ctrl-D on unix systems) causes EOF to reach, and you exit from the while
loop, but outside the while
loop you cannot read further input, since the EOF is already reached.
So to enable reading using cin
again, you need to clear eof
flag, and all other failure flags, as shown below:
cin.clear();
After doing this, you can start reading input using cin
once again!