2016-08-14 172 views
-3

我試圖做一個小例程,你輸入例如1 + 2和輸出應該是這兩個數字的總和。但它不斷崩潰,或者不會做任何事情。這是怎麼回事?爲什麼我的小程序崩潰?

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(){ 

char *op; 
char *first; 
char *second; 

printf("Enter operation\n"); 
scanf(" %s%s%s", &first, &op, &second); 

int num1; 
int num2; 
int num3; 
int add; 

num1 = atoi(first); 
num2 = atoi(op); 
num3 = atoi(second); 

add = num1 + num3; 


printf("Sum = %i\n",add); 

return 0; 
} 
+0

發佈完整的編譯輸出。閱讀:http://www.cplusplus.com/reference/cstdio/scanf/和一些關於C – Inline

+0

的好書,修正如[this](http://ideone.com/RKj9B1) – BLUEPIXY

回答

2

atoi採用參數作爲const char *而不是char。您的變量類型爲char,其中atoi將字符串轉換爲int類型。

同樣,您通過char *作爲%d的參數scanf,導致未定義的行爲。

scanf(" %d%d%d", &first, &op, &second) 
     ^^^^^^ expects int * not char *