Program crashes when trying to read numbers with scanf

五迷三道 提交于 2019-11-27 08:52:45

问题


A message like this appears, when i run this code. Project.exe has stopped working

Some of my other code works, but this seems to throw me an error.

#include<stdio.h> #include<conio.h>  void main() {     int n1, n2, sum;      puts("first number");     scanf("%d", n1);     fflush(stdin);     puts("second number");     scanf("%d", n2);     sum = n1 + n2;      printf("%d + %d = %d", n1, n2, sum);      getch();  } 

I basically want to add two numbers.


回答1:


scanf takes the address of the variable in which it stores the input value. You need to change your scanf calls to

scanf("%d", &n1); scanf("%d", &n2); //          ^ note the & operator 

Also, note that it's undefined behaviour to call fflush on an input stream. So, fflush(stdin) is not correct. You need to manually read and discard extraneous input left over in the stdin stream.



来源:https://stackoverflow.com/questions/23516761/program-crashes-when-trying-to-read-numbers-with-scanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!