2012-09-10 83 views
0

下面是一个简单的家庭作业问题,我有一个介绍CS类:C++分段故障

#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; 
} 

我不是很熟悉分段错误,所以如果有人可以解释,如果我做错了它” d太棒了。

+5

你输入什么? – chris

+4

http://en.wikipedia.org/wiki/Segmentation_fault –

+3

编译你的程序时启用调试信息和警告(例如Linux上的'g ++ -Wall -g'),然后学习使用调试器(例如Linux上的'gdb' )。 –

回答

-2

cin会尽量把多个字符在oper,你需要焦炭的矢量认为cin将投入它的所有字符(包括换行符)

在这种情况下,你可以使用char oper[10]将能够处理您正在尝试的一个字符输入。然而,我会建议使用std :: getline();如果使用std :: getline();我会建议使用std :: getline();如果使用std :: getline (http://www.cplusplus.com/reference/string/getline/

+1

'cin >>操作符;''将提取一个字符,不再提供,因为'操作符'是一个'字符'。这里有一个[示例](http://ideone.com/b4tBw)。 – chris

0

我在代码中找不到错误。 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; 

} 
+2

在评论中明确讨论了OP的问题,仅仅发布完全不同的工作代码就不是答案。 –

1

你的代码不能用gcc 4.1.2编译。你使用什么编译器?另外,“if(oper ='+')”对我来说看起来不正确。你想给那里的变量操作符赋“+”吗?

-1

更改如下:

if (oper == '+') 

else if (oper == '-') {} 
else if (oper == '*') {} 
else if (oper == '/') {} 
else if (oper == '%') {} 

使用'的人物和==布尔逻辑!

+0

这是他的代码中的一个错误,但不能在指定的行上引起段错误。 – djechlin