About terminating a while(cin >> s) loop

Hello to everybody,

This is my first post in the forum. I will try to be brief.

I wrote a small program in order to get string input from keyboard. My question is how do I get beyond the while loop.
1
2
3
4
    string s;
    while(cin >> s)
        cout << "\n" << s << "";
    code_after


The problem only occurs when I use string not other primary types (like int, double etc) because at least in those cases eof works. But as I can see when string are used eof
use is vain. I guess it's a simple problem but I can figure out a direct solution. I have come up with an if block inside while loop to check for a certain string and then use break;.

Thanks in advance for any reply.
have you tried char? if you're using only int or double then it make sense:
1
2
int s;
while (cin >> s)

while will break if the input is not an integer...

rather than:

1
2
string s;
while (cin >> s)

will never break the whilebecause string accept all types of data as if it's a sentence

CMIIW
Last edited on
Ok thanks for the quick answer. I am not fully covered though.

I got this fragment of code from "Accelerated C++" in 7.2 paragraph. The example as given there is not fully functional since I cannot get through while loop. In a general situation char may work but I don't get why would they provide a non-functioning code.
What are you trying to do? If you're trying to read in a line and then display it, I recommend using getline(cin, s), but if you're trying to read a single letter it would be better to just use a char. If you're trying to accomplish input checking, cin will store any single input in a char in it ASCII value, so there is no need for that loop. If you're trying to just have the console echo your input, then end at a certain point, you'll have to use your Operating System's End of File command. (Windows: Ctrl-Z | Linux: Ctrl-D | Mac OS X: Ctrl-D) When you use cin in a place where a bool is expected, it automatically converts to bool which, I believe (I'm on a computer where I cannot check at the moment), is the same value of cin.good(), so you can end a loop this way by using the appropriate command and setting the eof flag.
EOF should still work if you use std::string.
Ok thanks again.

To be clear I just wanted to realise why a code from a book wasn't working, that's why I did not use char or another approach.

From the solutions given I tried Ctrl-D (I'm in Linux) and worked fine. I guess that's what I was looking for.
For completeness reason to mention that neither EOF nor eof nor end-of-file works in that case.
Ctrl-D is EOF (in Linux).

Unless you hit Ctrl-D (EOF) then the loop should not terminate as long as it reads a legal value. And all values are legal for a std::string.
Last edited on
Topic archived. No new replies allowed.