scanf函数不读输入 [英] scanf not reading input

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

问题描述

我读到scanf函数更多的线程,我发现一些答案的机器人没有帮助我:

I read more threads about scanf and I found some answers bot none helped me:

while(!comanda){
    int tmp;
    if (scanf("%d", &tmp) == 0)
        getchar();
    else{
        comanda = tmp;
        fprintf(stdout,"%d",&comanda);
        fflush(stdout);}
    }
}

问题是,code这行之后得到执行,没有任何反应。这之后,我对comanda而无法执行检查。

The problem is that after this lines of code get executed, nothing happens. After this I have a check on "comanda" which does not execute.

推荐答案

一与 scanf函数的问题,所有的格式输入功能的是终端往往行模式操作或煮熟模式和API被设计为原料模式。换句话说, scanf函数实现通常不会返回,直到遇到一个换行符。输入缓冲和未来调用 scanf函数会消耗缓冲线。请看下面的程序:

One of the problems with scanf and all of the formatted input functions is that terminals tend to operate in line mode or cooked mode and the API is designed for raw mode. In other words, scanf implementations generally will not return until a line feed is encountered. The input is buffered and future calls to scanf will consume the buffered line. Consider the following simple program:

#include <stdio.h>

int main() {
    int a_number;
    printf("Enter a number: ");
    fflush(stdout);
    while (scanf("%d", &a_number) != EOF) {
        printf("you entered %d\n", a_number);
        printf("Enter another number: ");
        fflush(stdout);
    }
    return 0;
}

您可以前pressing输入多个号码<大骨节病>返回。下面是运行此程序的一个例子。

You can enter multiple numbers before pressing return. Here is an example of running this program.

bash$ gcc foo.c
bash$ ./a.out
Enter a number: 1 2 3 4 5 6 7 8 9 10<Return>
you entered 1
Enter another number: you entered 2
Enter another number: you entered 3
Enter another number: you entered 4
Enter another number: you entered 5
Enter another number: you entered 6
Enter another number: you entered 7
Enter another number: you entered 8
Enter another number: you entered 9
Enter another number: you entered 10
Enter another number: <Ctrl+D>bash$ 
bash$

scanf函数每次调用从输入流中读取一个数字,但在第一次调用才回来之后,我pressed <大骨节病>返回 。其余的调用立即返回而不阻塞更多的投入,因为输入流被缓冲,并且它可以从流读取另一个整数。

Each call to scanf read a single number from the input stream but the first call did not return until after I pressed return. The remaining calls returned immediately without blocking for more input because the input stream was buffered and it could read another integer from the stream.

解决这个问题的方案是使用与fgets ,并在同一时间处理整个数据线或使用的终端接口禁用的 规范输入处理。大多数人使用与fgets 因为POSIX的终端接口部分没有在Windows下实现的。

The alternatives to this are to use fgets and processing entire lines of data at one time or using the terminal interface to disable "canonical input processing". Most people use fgets since the terminal interface section of POSIX is not implemented under Windows.

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

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