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

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

问题描述

scanf(%d) scanf(%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,& j);

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 \n", j);

it将打印第一行,然后等待您输入数字,然后继续等待该数字之后的内容。所以,如果您只键入 5 Enter ,它似乎挂起了-您需要输入另一行带有非空格字符的行才能继续。如果再键入 6 Enter ,它将成为 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%转换也跳过了前导空格(除了%c %[%n ),空格之前%转换无关紧要(%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天全站免登陆