我的程序跳过获取输入数据吗? [英] My program skip getting input data?

查看:14
本文介绍了我的程序跳过获取输入数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的兑换货币的程序,可以买到啤酒。

但是程序中有一些东西,我不知道为什么,它会自动跳过第三个输入数据->结束程序。

这里是我的代码:

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

int main()
{
    int ex_rate_into_vnd = 20000; //! Exchange Rate
    int beer = 7000; //! Local price of a beer
    float in_c = 0; //! Input amount of money
    float out_c = 2; //! Amount of currency to exchange !
    float choice; //! Switch mode
    char buy; //! Deal or not

    //! Introduction
    printf ("||---------------------------------------------------||
");
    printf ("||         Currency Exchange Machine  beta           ||
");
    printf ("||---------------------------------------------------||
");

    printf ("Please choose your option:
");
    printf("	 1.Exchange VND to dollar
");
    printf("	 2.Exchange Dollar to VND
");

    do
    {
        printf("Your choice: ",choice);
        scanf("%f",&choice);
    } while( choice != 1 && choice != 2);

    printf ("Please enter amount of money:");
    scanf("%f",&in_c);

    if (choice == 1 )
        {
            out_c = in_c / ex_rate_into_vnd;
            printf ("Your amount of money: %.2f",out_c);
        }
    else
        {
           out_c = in_c * ex_rate_into_vnd;
           printf ("Your amount of money: %.0f",out_c);
        }
//! End of Exchanging

    printf ("
Would you like to buy a beer (y/n) ?",buy);
    scanf("%c", &buy);

    if (buy == 'y')
        {
        if (out_c >= 7000)
            {
                out_c = out_c - 7000;
                printf("Transactions success !
");
                printf("Your amount: %2.f",out_c);
            }
        }
    printf ("
Why Stop ?");


    return 0;
}

推荐答案

而不是scanf("%c", &buy);

1.在%c之前使用空格

scanf(" %c",&buy); //space before %c  
       ^ 

这将跳过读取空格(包括换行符)。

2.或在scanf("%c",&;Buy);语句之前使用getchar();

getchar(); //this hold the newline 
scanf("%c", &buy);

3.或使用两次getchar();

getchar();
buy=getchar();     
//here getchar returns int , it would be better if you declare buy with integer type.

在GCC中,fflush(stdin);的用法被摒弃。请避免使用它。

这篇关于我的程序跳过获取输入数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆