【问题标题】:char not working as expected in c [duplicate]char在c中没有按预期工作[重复]
【发布时间】:2016-12-13 08:54:57
【问题描述】:

您好,请考虑以下简单程序:

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

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

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

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

【问题讨论】:

  • 非常常见的常见问题解答。您在输入缓冲区中留下了换行符。例如,请参阅链接的副本,“当 *scanf() 无法按预期工作时”部分。

标签: c scanf fgets


【解决方案1】:

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

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

对于这种情况,getchar 前面的静默可以:

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

【讨论】:

  • 使用 fflush 不起作用,因为它没有为输入缓冲区定义。请从答案中删除该部分,因为它不正确并导致调用未定义的行为。
  • 啊对,fflush 不是标准的,tks。同意并删除那部分..
【解决方案2】:

输入第一个浮点数时有换行符,通过getchar调用以字符形式输入。解决此问题的另一种方法是使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2012-11-01
    • 2011-12-01
    • 1970-01-01
    • 2019-02-24
    • 2018-04-16
    • 2016-11-09
    相关资源
    最近更新 更多