问题
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