ç的getchar VS scanf函数 [英] C getchar vs scanf

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

问题描述

我被一块code的功能,我发现学习困惑:

 字符GetCommand(无效)
{
    字符的命令;    做{
        的printf(请输入命令(Q =退出,N =新,L =列表):);
        scanf函数(%C,&安培;命令);
        同花顺();
    }
    而((命令='Q')及!&安培;!(命令='N')
           &功放;&安培; (命令='L'!));    的printf(\\ n ---------- \\ n);
    返回(命令);
}同花顺无效(无效){
    而(的getchar()!='\\ n')
        ;
}

我不太明白这里是同花顺()函数的用法。我的意思是,这本书我读说它$ P $来自多个单字符输入更多的,然后有系统提示时,输入第二个时间读取字符的pvents用户解释它。

我不明白的是如何同花顺()是preventing这种情况的发生。它不会做任何事情。所有它是一个,而命令。 (虽然这是事实......什么?????)没有意义。


解决方案

的getchar()具有去除输入缓冲区的下一个字符的副作用。在循环刷新读取并放弃字符,直到 - 并包括 - 换行 \\ n 结束行

由于 scanf函数被告知要读一个且只有一个字符(%C ),这有效果忽略该输入行一切。

这可能会更清楚,如果scanf函数与替换

 命令=的getchar();

但它实际上是因为它没有处理完的文件以及一般坏榜样。

在一般 scanf函数最好遗忘; 与fgets 的sscanf 工作为一体,负责获取输入,另一个用于解析它好得多。 scanf函数(和的fscanf )尝试一次做太多的工作。

I am confused by a piece of code found in a function I am studying:

char GetCommand( void )
{
    char command;

    do {
        printf( "Enter command (q=quit, n=new, l=list):  " );
        scanf( "%c", &command );
        Flush();
    }
    while ( (command != 'q') && (command != 'n')
           && (command != 'l') );

    printf( "\n----------\n" );
    return( command );
}

void Flush( void ) {
    while ( getchar() != '\n' )
        ;
}

What I don't quite understand here is the usage of the Flush() function. I mean, the book I am reading explains it by saying that it prevents the user from inputting more than a single character and then having that character read when they are prompted for input the 2nd time.

What I don't understand is how Flush() is preventing this from happening. It doesn't DO anything. All it is is a while command. (While this is true......what?????) Doesn't make sense.

解决方案

getchar() has the side effect of removing the next character from the input buffer. The loop in Flush reads and discards characters until - and including - the newline \n ending the line.

Since the scanf is told to read one and only one character (%c) this has the effect of ignoring everything else on that input line.

It would probably be more clear if the scanf was replace with

command = getchar();

but it's actually a generally bad example as it does not handle End Of File well.

In general scanf is best forgotten; fgets and sscanf work much better as one is responsible for getting the input and the other for parsing it. scanf (and fscanf) try to do too many jobs at once.

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

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