将格式字符串作为命令行参数传递给 scanf 与硬编码相比

问题描述 投票:0回答:1

我有以下代码:

#include <stdio.h>
int main()
{
    int i;
    char c;
    char *format_string = "%d\n";
    scanf(format_string, &i);
    printf("read: %d\n", i);

    printf("Let's check what is in the input buffer:\n");
    while (scanf("%c", &c) == 1)
    {
        printf("read from input buf: %d\n", c);
    }
}

如果我按照以下方式运行代码:

echo "5" | ./specific.out

输出如下:

read: 5
Let's check what is in the input buffer:

这里我有上面代码的更通用版本,我从命令行传递格式字符串:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        exit(EXIT_SUCCESS);
    }

    int i;
    char c;

    char *format_string = argv[1];

    scanf(format_string, &i);
    printf("read: %d\n", i);

    printf("Let's check what is in the input buffer:\n");
    while (scanf("%c", &c) == 1)
    {
        printf("read from input buf: %d\n", c);
    }
}

如果我按照以下方式运行代码:

echo "5" | ./general.out '%d\n'

输出如下:

read: 5
Let's check what is in the input buffer:
read from input buf: 10

为什么我得到不同的输出?

c scanf
1个回答
1
投票

当您在命令行上指定

'%d\n'
时,您不会发送
%
后跟
d
后跟换行符。您发送
%
,然后是
d
,然后是
\
,然后是
n

因此,

echo
命令生成的换行符与格式字符串中的任何内容都不匹配(特别是换行符与
\
不匹配),因此它留在输入缓冲区中。

© www.soinside.com 2019 - 2024. All rights reserved.