December 11th, 2013, 05:53 PM
Breaking out of loop
Hi everyone, I have C++ primer 5th edition and doing a couple of examples in chapter three. The code has a while loop and I know how to break out of it by using ctrl z, but the code in the book doesn't use it. Is there something I am not doing or did they probably assume the reader would know? here is the code from the book.
while(cin >> word)
for(int i = 0; i < text.size(); i++)
cout << text[i] << endl;
December 14th, 2013, 06:27 AM
Re: Breaking out of loop
cin is a c++ file stream. A file stream has 4 possible states - good (available for use), eof (end of file has been reached), fail (logical error on i/o operation) and bad (read/write error on i/o operation).
Simplistically, when using stream extraction, if the state of the stream is good, then it returns a reference to the stream (which is non-zero). If stream is in one of the other states, stream extraction returns NULL (0). Hence the while condition is satisified as long as the stream is in the good state.
If you get a bad state, then something is wrong as this usually means that an expected i/o operation has gone wrong (often due to hardware problems). If the state is fail, then this usually means that you are trying to extract a type incompatible with the data available (ie trying to extract an int when the data is abc). If the state is eof, then the end of data has been reached. This is most often used when reading from files as opposed to the keyboard as for cin.
So to terminate the while loop, the state of cin has to changed from good to one of the other states. As you are are extracting a type string, really the only non-good state available is eof - as string will accept any character so you can't 'induce' a fail state (if you were reading a set of say integers, then you could terminate the loop by entering a non-numeric value). To induce an eof state from the keyboard, you use ctrl z as you state in your post.
To terminate a loop like this without inducing an eof, another way is use a special 'input sequence' (or sentinel value http://en.wikipedia.org/wiki/Sentinel_value) to terminate the loop. In this case you could check to see if the extracted string was, say, 'endofloop' and if it was equal to this value then terminate the loop.
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
December 14th, 2013, 05:45 PM
Re: Breaking out of loop
Originally Posted by 2kaud
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.