下面是一个简单的 CS 入门课作业问题:
#include <iostream>
#include <string>
int main() {
using namespace std;
int num1; int num2; int num3; int ans;
char oper;
/*
cout << "Enter an arithmetic expression:" << endl;
cin >> oper >> num1 >> num2 >> num3;
DEBUGGING
*/
cout << "enter an operator" << endl;
cin >> oper; /* Segmentation error occurs here... */
cout << "enter number 1" << endl;
cin >> num1;
cout << "enter number 2" << endl;
cin >> num2;
cout << "enter number 3" << endl;
cin >> num3;
cout << "okay" << endl;
if (oper = "+") {
if (num1 + num2 != num3) {
cout << "These numbers don't add up!" << endl;
}
else {
ans = num1 + num2;
cout << num1 << "+" << num2 << "==" << ans << endl;
}
}
else if (oper = "-") {}
else if (oper = "*") {}
else if (oper = "/") {}
else if (oper = "%") {}
else {
cout << "You're an idiot. This operator clearly does not exist... Try again " << endl;
}
return 0;
}
我对分段错误并不是很熟悉,所以如果有人能解释我是否做错了什么,那就太棒了。