char没有像c中预期的那样工作

时间:2016-12-13 08:54:58

标签: c scanf fgets

您可以考虑下面的简单程序:

int main(void)
{
    //exercise 1

    float num2;
    printf("please enter a number \n");
    scanf_s("%f", &num2);
    printf("the number multiple by 3 is %3.3f\n", num2 * 3);

    //exercise 2
    char ch1, ch2, ch3, ch4;

    printf("enter a word with four char\n");
    ch1 = getchar();
    ch2 = getchar();
    ch3 = getchar();
    ch4 = getchar();

    printf("the chars in reverse order are\n");
    putchar(ch4);
    putchar(ch3);
    putchar(ch2);
    putchar(ch1);
    putchar('\n');
}

输出是:

please enter a number
2
the number multiple by 3 is 6.000
enter a word with four char
ffff
the chars in reverse order are
fff

如果我将练习2的代码块移到1以上,则将3个字符打印到控制台:

int main(void)
{
    //exercise 2
    char ch1, ch2, ch3, ch4;

    printf("enter a word with four char\n");
    ch1 = getchar();
    ch2 = getchar();
    ch3 = getchar();
    ch4 = getchar();

    printf("the chars in reverse order are\n");
    putchar(ch4);
    putchar(ch3);
    putchar(ch2);
    putchar(ch1);
    putchar('\n');

    //exercise 1

    float num2;
    printf("please enter a number \n");
    scanf_s("%f", &num2);
    printf("the number multiple by 3 is %3.3f\n", num2 * 3);
}

预期的结果:

enter a word with four char
ffff
the chars in reverse order are
ffff
please enter a number
2
the number multiple by 3 is 6.000

我想知道为什么当我更改代码块的顺序时它会起作用,我该怎么解决它,谢谢。

2 个答案:

答案 0 :(得分:4)

  

想要知道为什么当我更改代码块的顺序时它会起作用,我该如何解决呢?

那是因为scanf_s("%f", &num2);在输入缓冲区中留下了换行符。因此,您的第一个getchar();会将该换行解释为ch1

对于这种情况,前一个getchar之前的静音会:

getchar();  // will consume the remaining newline from stdin
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();

答案 1 :(得分:2)

输入第一个浮点数时会出现换行符,并且通过调用getchar将其输入为char。另一种解决方法是使用fgets将整行作为字符串,然后用您想要的任何格式解析它:

char line[512];
printf("please enter a number \n");
fgets(line, sizeof line, stdin);    // the newline is consumed here
sscanf(line, "%f", &num2);

ch1 = getchar(); // working as expected
相关问题