scanf("%d", &value)中的字符输入 [英] Character input in scanf("%d", &value)

查看:88
本文介绍了scanf("%d", &value)中的字符输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我的代码是,

In brief my code is,

#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    while(n != 0)
    {
        scanf("%d", &n);
        printf("%d\n", n);
    }
    return 0;
}

它是为 integer 输入编写的.但是如果我输入一个 character 代替(尽管 n 被清除为 integer),循环会无限循环并打印最后一个 integer 输入值.如果我首先输入 character ,它似乎打印了一个内存地址.我的问题是,如果我输入 character 而不是 integer 会发生什么?

It was written for integer input. But if I input a character instead (although n is decleared as integer), the loop goes infinite and prints the last integer input value. If I input a character at first it seems like it prints a memory address. My question is, what is happening here if I input a character instead an integer?

推荐答案

当 scanf 失败时,它不会从输入缓冲区中删除字符(它会在成功时从缓冲区中删除数据).因此,下次在循环中触发 scanf 时,它根本不会等待用户输入(因为它的缓冲区中有一个未读字符).但它一次又一次地失败(因为每次都失败),因此将进入无限循环.

我坚信第一个 scanf 包含 %c 作为格式说明符.
你可以通过

When scanf fails, it does not remove the character from input buffer (It does remove data from buffer when it succeeds). So, the next time scanf is triggered in the loop, it will not wait for user input at all (since it has an unread character in its buffer). But it fails again, and again (since everytime it fails) and hence will go into an infinite loop.

I strongly believe the first scanf contains %c as format specifier.
You can get rid of infinite loop by

if(scanf("%d",&n)==0) break;

这篇关于scanf("%d", &amp;value)中的字符输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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