scanf函数被忽略 [英] Scanf is being ignored

查看:107
本文介绍了scanf函数被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#define length 20
main()
{
    float x;
    int y;
    float array1[length], array2[length], array3[length];
    float ray[length];
    int size1 = insert(array1, length);
    printf("enter number: ");
    scanf("%d", &y);
    int size2 = insert(array2, length);
    int size3 = insert(array3, length);
}

int insert(float a[], int size)
{
    int  n = 0;
    while(n<size && scanf("%f\n", &a[n]) == 1)
    {
        printf("you entered: ");
        printf("%2.1f\n", a[n]);
        n++;
    }
    return n;
}

当我运行该程序,执行第一次插入没关系,但下次调用函数时, scanf()的似乎被完全忽略。我试图把它的权利,其中插入完成后,但是这忽略了为好。

When I run the program, it executes the first insert okay, but the next time function is called, scanf() seems to be ignored completely. I tried putting it right after where insert is done, but that's ignored as well.

推荐答案

使用%* C中scanf的消耗与换行符%左右三维空间沿主的scanf()的。我测试MingW平台上下面code和它似乎工作。在scanf函数中的'\\ n'被消耗使得scanf()的返回,而'\\ n'在回车键的preSS仍()再次保持在由scanf函数消耗IO缓冲;因此怪异的行为。

Use %*c in scanf to consume the newlines along with space around %d in the scanf in main(). I tested the below code on MingW and it seem to work. The '\n' in your scanf is being consumed making it scanf() return while the '\n' at the press of enter key still remains in IO buffer to be consumed by scanf() again; hence the weird behaviour.

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

#define length 20

int insert(float *a, int size)
{
    int  n = 0;
    while(n<size && scanf("%f%*c", &a[n]))
    {
        printf("you entered: ");
        printf("%2.1f\n", a[n]);
        n++;
    }
    return n;
}

int main(int argc, char* argv[])
{
float x;
    int y;
    float array1[length], array2[length], array3[length];
    float ray[length];
    int size1 = insert(array1, length);
    printf("enter number: ");
    scanf("%d", &y);
    int size2 = insert(array2, length);
    int size3 = insert(array3, length);
    return 0;    
}

这篇关于scanf函数被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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