【问题标题】:C: Unable to receive input using scanf() [duplicate]C:无法使用scanf()接收输入[重复]
【发布时间】:2016-09-15 18:43:42
【问题描述】:
#include<stdio.h>

int main()
{

    float p, r, t;
    char ch = 'y';

    do
    {
        printf("Enter principal: ");
        scanf("%f", &p);

        printf("Enter rate: ");
        scanf("%f", &r);

        printf("Enter t: ");
        scanf("%f", &t);

        printf("SI = %f", (p *r * t)/100 );

        printf("\nCalculate SI one more time ? ('Y' for Yes, 'n' for no ) : ");
        ch = getchar();


    }while(ch == 'y'); 

    return 0;

}

输出:

Enter principal: 1334
Enter rate: 4
Enter t: 2
SI = 106.720000
Calculate SI one more time ? ('Y' for Yes, 'n' for no ) :
Process returned 0 (0x0)   execution time : 5.359 s
Press any key to continue.

如您所见,我无法第二次计算 SI?有什么问题?

我什至尝试用 scanf() 替换 getchar() 但它仍然无法正常工作

【问题讨论】:

  • ch = getchar(); 在输入缓冲区中仍有一个newline,由前一个scanf 留下。
  • @WeatherVane 你能解释一下发生了什么吗?
  • 大多数格式的 scanf(但不是 %c)会占用 leading 空格,但会在输入缓冲区中留下任何后续内容。基于字符的输入函数,取其所有。
  • @WeatherVane 有什么解决办法
  • scanf(" %c", &amp;ch); 注意%c 之前的空格,它会像其他格式说明符一样吃掉前导空格。

标签: c scanf


【解决方案1】:

scanf 在数字完成时停止读取(在第一个不能成为其中一部分的字符处)。

所以你的最后一个scanf (for t) 停止在你输入 t 值后按下的 RET 之前读取。 getchar() 然后读取下一个字符,这是一个 '\n'(RET),它不等于 'y',所以它结束了。

您不应该混合使用多种输入法;如果您使用scanf,请使用scanf,并让它读取一个字符(scanf(" %c",&amp;ch);)或其他解决方案;或阅读'\n',在scanf 后面加上一个额外的getchar() 并忽略它。

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    相关资源
    最近更新 更多