0

Both expresions from a reference book (www.bogotobogo.com/cplusplus/files/ThinkingInCPlusPlusVolumeOne.pdf) I tried but work badly, looks like reads keyboard but nor c neither x got the value of the key pressed. Editor (VS 2019 Win 10) don't identify as mistake, debugger reveals that c or x don't receive the value.

full sample program is:

//: C03:OnTheFly.cpp
// On-the-fly variable definitions
 #include <iostream>
 using namespace std;  
 int main()
 {
   //..   { // Begin a new scope     int q = 0; // C requires definitions here
   //..     // Define at point of use:
   for(int i = 0; i < 100; i++)
     { 
         q++; // q comes from a larger scope
              // Definition at the end of the scope:
         int p = 12;
      }
      int p = 1;  // A different p
    } // End scope containing q & outer p
   cout << "Type characters:" << endl;
   while(char c = cin.get() != 'q')
   {     
        cout << c << " wasn't it" << endl;
        if(char x = c == 'a' || c == 'b')
           cout << "You typed a or b" << endl;
        else
           cout << "You typed " << x << endl;
   }   
   cout << "Type A, B, or C" << endl;
   switch(int i = cin.get())
   {     
       case 'A': cout << "Snap" << endl;
       break;
       case 'B': cout << "Crackle" << endl;
       break;
       case 'C': cout << "Pop" << endl;
       break;
       default: cout << "Not A, B or C!" << endl;
   }
}
///:~ 

Is some problem of version of C++ ? I tried with dafault option for C++ version ant also with C++11, C++14, C++17.

Anxon Pués
  • 117
  • 5
  • 1
    That's not a reference book, it's an ancient beginners' introduction to C++ 03. – molbdnilo Oct 26 '19 at 14:44
  • 4
    `c = cin.get() != 'q'` is the same as `c = (cin.get() != 'q')` because of operator precedence. Don't write complex assignments in conditional clauses - you create bugs like this. I have no idea why this style is taught so much - it's horribly bug-prone and prevents line-by-line debugging. – Andrew Henle Oct 26 '19 at 14:45
  • 3
    Just to enlarge on @Andrew's comment: if you rearrange the parentheses to `(c = cin.get()) != 'q'`, it works. – TonyK Oct 26 '19 at 14:47
  • There's a not very obvious hint on the next page ("the results are not what you might like") that the condition doesn't actually work in that way. (Moral of this story: always read the text in a textbook.) – molbdnilo Oct 26 '19 at 14:50
  • @molbdnilo I will appreciate any advice of better source of recent C++ that fits better, I had not wrote code for several years ( like 20 or so) and as I am retired like to recover some knowledge... thanks in advance – Anxon Pués Oct 26 '19 at 14:54
  • 1
    See https://stackoverflow.com/a/388282/5699329 – rsjaffe Oct 26 '19 at 14:57

0 Answers0