What's wrong with cin >> num1, num2?

后端 未结 3 1972
予麋鹿
予麋鹿 2021-01-26 05:42
#include 
using namespace std;

int main() {
  char choice;
  int solution, num1, num2;

  cout << \"Menu\";
  cout << \"\\n========\";
  cou         


        
相关标签:
3条回答
  • 2021-01-26 06:22
    cin >> num1, num2;
    

    This syntax is not correct for what you want. To chain, use

    cin >> num1 >> num2;
    

    If you compile with warnings you'll get notified about this by the compiler

    int a{}, b{};
    std::cin >> a, b;
    

    gives the error:

    warning: right operand of comma operator has no effect [-Wunused-value]
    std::cin >> a, b;
    

    The whole statement is parsed as

    ((std::cin >> a), b);
    

    Which consists of two comma-separated expressions. The b in that case doesn't have any effect. If you print the variables after the std::cin line above, you will always get 0 for b

    0 讨论(0)
  • 2021-01-26 06:25
    int solution, num1, num2;
    

    This leaves all variables uninitialised. Trying to read from them without a previous assignment is undefined behaviour.

    cin >> num1, num2;
    

    The supposed intention of this line is to read into both variables. What happens really is an application of the comma operator, with operands cin >> num1 on the left side and num2 on the right side.

    The left side is evaluated and a value is written to num1; the second operand has no effect and leaves num2 in its uninitialised status.

    It's as if you had written cin >> num1;.

    solution = num1 + num2;
    

    The aforementioned undefined behaviour happens, rendering your entire program invalid.

    You can fix the problem as follows:

    cin >> num1;
    cin >> num2;
    
    0 讨论(0)
  • 2021-01-26 06:32

    You are using cin wrong. Do this instead :

    cin >> num1 >> num2;
    

    (And it is always nice to let the user know what to type with one cout or two :)).

    You could do cin only once just after cin >> choice, and before the switch. It will save you some lines and will respect the credo :

    Do not repeat yourself.

    You don't check for divide by zero. If the user try to do num1 / 0, your program will crash.

    The return 0 in case 'X' is not necessary and your break won't be reached, so you could remove the return and you will meet the main's return 0 instead, keeping the switch nice and clean.

    In case '/' you cast num2 to double. I don't see why you print the result of a int casted to a double. My guess is you wanted the result to be a double. In that case, you would do :

    solution = num1 / (double)num2; 
    

    and change solution to be a double.

    Lastly, I advise you always initialize your variables since you could face the case where you use unitialized variables and get undefined behavior.

    0 讨论(0)
提交回复
热议问题