Thread: more C++ programming guidance

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    16

    more C++ programming guidance

    I am working on example7-6 from O'Reilly's Practical C++ Programming book. I am finding that I need to enter 'q' twice to quit the program, but the code says to me that I should only need to enter 'q' once. any clues what is going on here? I want the code to be written in a way that I only need to enter 'q' once.

    Thank you everybody for your assistance in advance.

    -- program output ---

    % ./calc3 Result: 0
    Enter operator and number: q
    q
    %

    --- snip ----


    Code:
    #include <iostream>
    
    int   result;      // the result of the calculations
    char  oper_char;   // operator the user specified
    int   value;       // value specified after the operator
    
    int main()
    {
    
      result = 0; // initialize the result
    
      // loop forever (or until break reached)
      while (true) {
        std::cout << "Result: " << result << '\n';
        std::cout << "Enter operator and number: ";
    
        std::cin >> oper_char >> value;
    
        if ((oper_char == 'q') || (oper_char == 'Q'))
          break;
    
        if (oper_char == '+') {
          result += value;
        } else if (oper_char == '-') {
          result -= value;
        } else if (oper_char == '*') {
          result *= value;
        } else if (oper_char == '/') {
          if (value == 0) {
            std::cout << "Error:Divide by zero\n";
            std::cout << "   operation ignored\n";
          } else
            result /= value;
        } else {
          std::cout << "Unknown operator " << oper_char << '\n';
        }
      }
      return (0);
    }

  2. #2
    Never Exist Hermitsky's Avatar
    Join Date
    Jul 2004
    Posts
    149
    std::cin >> oper_char >> value;
    this line put the first character into oper_char, and the next one into value.

    blow me ... ...

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    16
    somehting more like this appears to be working.

    Code:
        std::cin >> oper_char;
    
        if ((oper_char == 'q') || (oper_char == 'Q'))
          break;
    
        std::cin >> value;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some guidance.
    By Kinto in forum C Programming
    Replies: 10
    Last Post: 05-31-2009, 12:02 AM
  2. Guidance, please.
    By mattagrimonti in forum C Programming
    Replies: 2
    Last Post: 11-26-2008, 08:50 AM
  3. need guidance to connect to serial port
    By gnychis in forum Linux Programming
    Replies: 1
    Last Post: 06-02-2005, 10:10 AM
  4. Audio guidance.
    By Sebastiani in forum Windows Programming
    Replies: 6
    Last Post: 12-22-2002, 09:14 AM
  5. advice and possibly guidance
    By nazri81 in forum C++ Programming
    Replies: 3
    Last Post: 11-07-2002, 10:19 PM