While(cin)

May I know what does this code do? Just a beginner, but I have never used this code and would like to know how to use it or specifically what does it do? Importantly, just need to know while(cin) part.

1
2
3
4
5
  char ch;
  cin>>ch;

While (cin)
? I don't know if that will work, IMO the proper syntax should be :

1
2
3
4
5
char ch;

while ( cin >> ch ) {

}


Basically, this loop just ask for a char until EOF, so you must press Ctrl + D ( or Ctrl + Z ) in order to send EOF signal to stop this loop
One more question shadow fiend. What does it mean when I have an eof on files. For instance, infile.eof.

Does this mean that it will read data until no text is found?
are you refering to when reading files ?

1
2
3
while ( ! infile.eof() ) {
// ...
}


if that is what you mean , *yes, but not so true* and eof() in while loop condition is considered a bad practice :

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong?answertab=votes#tab-top
Yes, I was referring to that :) and I have the answer I was looking for:) Thank you :)
Had a quick question. I was looking over youtube videos and encountered this loops where they said this loop will be exceucuted until the number is zero. I know I didn't give out that many details of what my problem is; however, what does while(number) I thought if I don't want number to be zero can I not just do !number=0)

1
2
3
4
5
6
7
8
9
10
11

Cin>>number;
While(number)
{





}
I thought if I don't want number to be zero can I not just do !number=0)


yes.

 
while( number ) { ... }

and
 
while( !number == 0 ) { ... }


is basically just the same but it is used ( i think ) as a convention since !number == 0 is really less interpret-able compared to while ( number );

Hope this helps, just ask a question if something is not clear
It did help :) thank you :)
while(number) is valid, because 'number' is being evaluated as an expression, which can yield either true (non-zero value) or false (zero).

If number is 0, zero is not non-zero, therefore the expression is false, and the loop terminates.

If number is any non-zero value, the expression is true, and the loop continues.
Last edited on
Topic archived. No new replies allowed.