简体   繁体   中英

cin.get with logical operator in while loop

This program in C++ is very simple:

while (ch = cin.get())
 cout << ch;

If I put a character and then I press the Enter, I'll see this sign on the screen. For example:

w
w
k
k

I can change the code to the following form:

ch = cin.get();
 while (ch != 'q')
 {
  cout << ch;
  ch = cin.get();
 }

In this case the program will stop if I put the q letter. I tried to make a much shorter version of last program:

while (ch = cin.get() && ch != 'q')
 cout << ch;

Unfortunately this program doesn't print any character. If I put the letter and press the Enter, the cursor indicates new line on the screen (without printing) and the program waits for a new character. I don't understand why in this program the method "cin.get()" doesn't assign any character to the "ch" variable. Of course the type of ch is char.

If you look at C++'s operator precedence you'll see that && binds more strongly than = , which basically means your code is evaluated as...

while (ch = (cin.get() && ch != 'q'))

...not...

while ((ch = cin.get()) && ch != 'q')

You should add ( and ) as in the last line above.

What's actually been happening is that ch = cin.get() && ch != 'q' tests that it can get a character (likely true ), and that the character is not q ( true if the character doesn't just happen to have a q on the first while loop iteration when you read it seemingly uninitialised - which would be Undefined Behaviour - though perhaps you give it an initial value when you define it). true && true is true , so it's equivalent to ch = true . true is converted to char with ASCII value 1 ... your terminal might print something for that or not... it's not one of the normal "printable" (visible) ASCII codes. On the next loop iteration we know ch is 1 so it can never compare equal to q ... the only way to terminate now is if cin.get() fails due to an "end of file" condition - pressing control-D on UNIX/Linux or control-Z on Windows, or something that breaks the whole program out of the loop like control-C or a kill/end task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM