scanf() 格式字符串中尾随空格的影响是什么? [英] What is the effect of trailing white space in a scanf() format string?

查看:22
本文介绍了scanf() 格式字符串中尾随空格的影响是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码中scanf("%d")scanf("%d")有什么区别,区别在于格式中的尾随空白字符串?

What is difference between scanf("%d") and scanf("%d ") in this code, where the difference is the trailing blank in the format string?

#include <stdio.h>

int main(void)
{
    int i, j;

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

当我在像 scanf("%d ", &j); 这样的格式说明符后添加空格时,scanf() 函数实际上是如何工作的?>

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.

使用您的代码:

printf("enter a value for j ");

scanf("%d  ",&j);

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

它会打印第一行,然后等你输入一个数字,然后在数字之后继续等待.因此,如果您只输入 5Enter,它似乎会挂起 — 您需要在另一行中输入一些非空白字符才能继续.如果然后键入 6Enter,它将成为 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),空格 before %-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() 格式字符串中尾随空格的影响是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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