C++分段故障
下面是一个简单的作业问题,我有一个介绍CS类:C++分段故障,c++,segmentation-fault,C++,Segmentation Fault,下面是一个简单的作业问题,我有一个介绍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 >&
#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;
}
我不太熟悉分割错误,所以如果有人能解释我做错了什么,那就太棒了 cin将尝试在oper中放入多个字符,您需要一个字符向量来保存cin将放入的所有字符,包括换行符
在这种情况下,您可以使用char oper[10],它将能够处理您正在尝试的单字符输入
然而,我建议使用std::getline 我在代码中找不到错误。VC++
#include <iostream>
#include <string>
int main() {
using namespace std;
int num1; int num2; int num3=0; int ans;
char oper;
cout << "Enter an arithmetic expression: ( [/ 4 2] or [+ 1 1] or [- 5 4] )" << endl;
cin >> oper >> num1 >> num2;
switch (oper)
{
case '+':
ans=num1+num2 ;
break;
case '-':
ans=num1-num2 ;
break;
case '*':
ans=num1*num2 ;
break;
case '/':
ans=num1/num2 ;
break;
}
cout << "\nans= " << ans<<"\n\n";
return 0;
}
您的代码不使用GCC4.1.2进行编译。你在用什么编译器?另外,如果oper='+'在我看来是不正确的。是否将“+”赋值给变量oper?更改以下内容:
if (oper == '+')
else if (oper == '-') {}
else if (oper == '*') {}
else if (oper == '/') {}
else if (oper == '%') {}
将“”用于字符,将==用于布尔逻辑 输入的内容是什么?在编译程序时启用调试信息和警告,例如Linux上的g++-Wall-g,然后学习在Linux上使用调试器,例如gdb。您能否发布一个完整的、可编译的示例来演示错误,并准确地告诉我们您在出错时给出的输入。@Briancollete,Ohh,您正在将单个字符与字符串文字进行比较。那太糟糕了。您应该对字符使用单引号:“c”.cin>>oper;将提取一个字符,不再提取,因为oper是字符。这里有一个问题。评论中清楚地讨论了OP的问题,仅仅发布完全不同的工作代码并不是一个答案。这是他的代码中的一个错误,但不能在指示的行上导致segfault。