试图读取与scanf的号码时,程序崩溃 [英] Program crashes when trying to read numbers with scanf

查看:282
本文介绍了试图读取与scanf的号码时,程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出现这样的消息,当我运行该code。
Project.exe已停止工作。

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

我的一些其他code的作品,但这似乎把我的错误。

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.

推荐答案

scanf函数发生在其存储输入值的变量的地址。你需要改变你的 scanf函数来电

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

另外请注意,这是不确定的行为叫 fflush 上的输入流。因此, fflush(标准输入)是不正确的。您需要手动读取并丢弃标准输入流中遗留下来的多余输入。

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.

这篇关于试图读取与scanf的号码时,程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆