有什么scanf函数之间的差异(QUOT;%D")和scanf(QUOT;%D")? [英] What is difference between scanf("%d") and scanf("%d ")?

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

问题描述

#include <stdio.h>

int main(void)
{
    int i, j;

    printf("enter a value for j ");
    scanf("%d  ",&j);
    printf("j is %d \n", j);
    printf("enter a value for i ");
    scanf("%d",&i);
    printf("i is %d \n", i);
    return 0;
}

如何在 scanf()的函数实际上,当我的格式说明像 scanf函数(%D之后添加空格,与放工作;Ĵ );

How does the scanf() function actually work when I add spaces after the format specifier like scanf("%d ",&j);?

推荐答案

在scanf格式空格字符,使其明确地阅读,而忽略尽可能多的空白字符,因为它可以。因此,与 scanf函数(%d个,... ,读了许多之后,它将继续读取字符,丢弃所有空白,直到它看到一个非空白字符输入,即非空白字符将被留作为下一个字符由一个的输入功能来读取。

A whitespace character in a scanf format causes it to explicitly read and ignore as many whitespace characters as it can. So with scanf("%d ", ..., after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input. That non-whitespace character will be left as the next character to be read by an input function.

通过您的code:

printf("enter a value for j ");

scanf("%d  ",&j);

printf("j is %d \n", j);

将打印的第一行,然后等待你输入一个数字,然后的后继续的数量要等待的东西。所以,如果你只需要输入<大骨节病> 5 <大骨节病>输入,它会出现挂 - 你需要输入一些非空白字符它继续另一条线。如果然后键入<大骨节病> 6 <大骨节病>输入,这将成为 i的值,让你的屏幕看起来是这样的:

it will print the first line and then wait for you to enter a number, and then continue to wait for something after the number. So if you just type 5Enter, it will appear to hang — you need to type in another line with some non-whitespace character on it to continue. If you then type 6Enter, that will become the value for i, so your screen will look something like:

enter a value for j 5
6
j is 5
enter a value for i i is 6

此外,由于大多数scanf函数%-conversions也跳过前导空白(所有除了%C %[%N ),空格的的%-conversions是无关的(%D%D将相同的行为)。因此,在大多数情况下,你应该避免在scanf中的转换空间,除非你知道你特别需要他们的奇特效果。

Also, since most scanf %-conversions also skip leading whitespace (all except for %c, %[ and %n), spaces before %-conversions are irrelevant ("%d" and " %d" will act identically). So for the most part, you should avoid spaces in scanf conversions unless you know you specifically need them for their peculiar effect.

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

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