scanf() 函数的一些问题

Some trouble with scanf() function

你可能看起来很简单,但我真的不明白哪里不对。 为什么我为 b 输入的值分配给了 h? 也就是说,我不能再进入步骤。程序立即输出一行。有什么问题?

int main(int argc, char** argv) {
    double a, b, h, x, x1, E;
    printf(" Input eps:");
    scanf("%lf", &E);
    printf(" Input [a,b]:");
    scanf("%lf,%lf", &a, &b);
    printf(" Step :");
    scanf("%lf", &h);
    printf ("%lf,%lf,%lf,%lf", E, a, b, h);
    return 0;
}

scanf("%lf,%lf",&a,&b);

格式字符串中的那个逗号意味着您需要输入一个逗号。否则在一项后扫描失败,在输入流中留下 5

如果您检查 scanf 的 return 值,您会发现它是一个而不是两个。这就是为什么 b 为零(尽管它可以是任意值,因为您没有对其进行初始化)并且输入流中剩余的 5 被用于 以下 [=38] =] scanf 填充 h.

最简单的解决方法可能就是使用 "%lf %lf",并使用 space 而不是逗号。 White space 不被认为是对确切字符的字面要求,它会简单地跳到第一个非 whitespace 字符。来自 scanf 指令的 ISO C11 标准:

The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification.

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If any of those characters differ from the ones composing the directive, the directive fails and the differing and subsequent characters remain unread.

A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier.

逗号既不是白色的space也不是转换规范(以%开头),属于上面“普通多字节字符”段落的范围。


顺便说一句,下面的程序说明了这一点:

#include <stdio.h>

int main()  {
    double d1 = 999, d2 = 998;
    printf("Enter two doubles: ");
    int count = scanf("%lf,%lf", &d1, &d2);
    printf("count = %d, d1 = %f, d2 = %f\n", count, d1, d2);

    printf("Rest of input line is: [");
    int ch;
    while ((ch = getchar()) != '\n') {
        putchar(ch);
    }
    puts("]");

    return 0;
}

这会在我的系统上产生以下结果:

pax:/home/pax> ./testprog # with space separator
Enter two doubles: 4.6 9.2
count = 1, d1 = 4.600000, d2 = 998.000000
Rest of input line is: [ 9.2]

pax:/home/pax> ./testprog # with comma separator
Enter two doubles: 4.6,9.2
count = 2, d1 = 4.600000, d2 = 9.200000
Rest of input line is: []

您代码的 scanf("%lf,%lf",&a,&b); 行中的第一个 %lf 和第二个 , 之间不需要逗号 ,。它应该改为使用 "%lf%lf""%lf %lf".

在它们之间使用逗号的问题在于它会跳过b的用户输入并直接接受h的输入。