cin>>怎么了?num1,num2? [英] What's wrong with cin >> num1, num2?

查看:77
本文介绍了cin>>怎么了?num1,num2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

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

  cout << "Menu";
  cout << "\n========";
  cout << "\n+) Add";
  cout << "\n-) subtract";
  cout << "\n*) Multiplication";
  cout << "\n/) Division";
  cout << "\nx) Exit";
  cout << endl;
  cout << "\nEnter your choice: ";
  cin >> choice;

  switch (choice) {
    case '+':
      cout << "\nEnter the operands: ";
      cin >> num1, num2;
      solution = num1 + num2;
      cout << num1 << '+' << num2 << '=' << solution;
      break;
    case '-':
      cout << "\nEnter the operands: ";
      cin >> num1, num2;
      solution = num1 + num2;
      cout << num1 << '-' << num2 << '=' << solution;
      break;
    case '*':
      cout << "\nEnter the operands: ";
      cin >> num1, num2;
      solution = num1 * num2;
      cout << num1 << '*' << num2 << '=' << solution;
      break;
    case '/':
      cout << "\nEnter the operands: ";
      cin >> num1, num2;
      solution = num1 / num2;
      cout << num1 << '/' << (double)num2 << '=' << solution;
      break;
    case 'x':
    case 'X':
      cout << "\nExiting....";
      return 0;
      break;
    default:
      cout << "\nInvalid choice";
  }

  return 0;
}

所以我正在写一个程序,允许用户输入操作.它几乎是一个计算器!我必须使用switch语句.我觉得我已经很近了,但是现在我撞到了砖墙.用户输入操作后,程序将运行并说要输入操作数,然后应使用输入的数字进行操作并显示出来.在用户输入程序刚崩溃的2个操作数之后,Theere是某种类型的问题.有什么建议吗?

So i am writing a program which allows the user to input an operation. Its pretty much a calculator! I must use a switch statement. I feel like I am very close but now i have hit a brick wall. After the user inouts an operation the program runs and says it to enter the operands it is then supposed to do the operation with the numbers entered and the displays them. Theere is some type of problem after the user inputs the 2 operands where the program just crashes. Any suggestions as to what it may be?

推荐答案

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;

给出错误:

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

整个语句被解析为

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

其中包含两个逗号分隔的表达式.在这种情况下, b 无效.如果您在上面的 std :: cin 行之后打印变量,则对于 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

这篇关于cin&gt;&gt;怎么了?num1,num2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆