scanf的之间差(QUOT;%C&QUOT ;,和C)和scanf(QUOT;%C&QUOT ;,和C) [英] Difference between scanf("%c", &c) and scanf(" %c", &c)

查看:124
本文介绍了scanf的之间差(QUOT;%C&QUOT ;,和C)和scanf(QUOT;%C&QUOT ;,和C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的C code片断:

Consider the following C code snippet:

#include <stdio.h>

int main()
{
    int a;
    char c;
    scanf("%d",&a);
    scanf("%c",&c);
    printf("int=%d\n",a);
    printf("char=%c\n",c);
}

我能够输入只整数而不是character.The输出是简单的整数值,没有值是用于第二printf语句输出

I'm able to input only the integer and not the character.The output is simply the integer value and no value is output for the second printf statement.

但是,如果我的格式说明符之前使用空格:

However if I use a space before the format specifier:

scanf(" %c",&c);

据按预期工作。为什么会出现这种情况?

It works as expected. Why is this the case?

有人告诉我,它是与清除输入缓冲区。可能有人提供一些线索上一样吗?

Someone told me it has something to do with clearing the input buffer. Could someone shed some light on the same?

推荐答案

之间的区别scanf函数(%C,&安培; C1) scanf的(%C,&放大器; c2)的是,没有空白的格式读取下一个字符,即使它是空白的,而一个具有空白跳过白色空间(包括换行),并读取下一个字符不是空白。

The difference between scanf("%c", &c1) and scanf(" %c", &c2) is that the format without the blank reads the next character, even if it is white space, whereas the one with the blank skips white space (including newlines) and reads the next character that is not white space.

scanf()的格式,为空格,制表或换行的意思是跳过空白,如果有任何跳过。它不直接地清除输入缓冲器,但它确实吃的任何空白看起来类似于清零输入缓冲器(但不同于截然不同)。如果你在Windows下使用 fflush(标准输入)清除(空白和非空白字符)的输入缓冲器;在Unix并根据C标准, fflush(标准输入)是未定义的行为。

In a scanf() format, a blank, tab or newline means 'skip white space if there is any to skip'. It does not directly 'clear the input buffer', but it does eat any white space which looks similar to clearing the input buffer (but is quite distinct from that). If you're on Windows, using fflush(stdin) clears the input buffer (of white space and non-white space characters); on Unix and according to the C standard, fflush(stdin) is undefined behaviour.

顺便说一下,如果你输入的整数紧跟一个回车,你的程序的输出与两个新行结束:第一次是在 C ,并在第二格式字符串。因此,你可能已经看到:

Incidentally, if you typed the integer followed immediately by a carriage return, the output of your program ends with two newlines: the first was in c and the second in the format string. Thus, you might have seen:

$ ./your_program
123
int=123
char=

$

也就是说, scanf()的读取换行符作为其输入。考虑另一种输入:

That is, the scanf() reads the newline as its input. Consider an alternative input:

$ ./your_program
123xyz
int=123
char=x
$

整数输入停止时,它读取的X;因此字符输入读取的X。

The integer input stopped when it read the 'x'; the character input therefore reads the 'x'.

这篇关于scanf的之间差(QUOT;%C&QUOT ;,和C)和scanf(QUOT;%C&QUOT ;,和C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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