0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "mainl.h"

static struct prod_details pd;

char *getinput(char *inp)
{
    printf("Enter the amount of the product %d:\n",pd.no_prod+1);
    gets(inp);
    return inp;
}

void print()
{
    printf("........................\n");
    printf("No of Product is: %d\n",pd.no_prod);
    printf("Grant Total is : %.2f\n",pd.total);
    printf("........................\n");
}

int check(char *str) 
{
    int i;
    if(strlen(str) == 0)
        return 2;
    for(i=0;i<strlen(str);i++)
    {
        if(str[i] == '-')
            return 3;
        if(isalpha(str[i]) != 0)
            return 0;
    }
    return 1;
}

void calc(char *str)
{
    pd.array[pd.no_prod]=atof(str);
    pd.total=pd.total+pd.array[pd.no_prod];
    printf("Total is:%.2f\n",pd.total);
    pd.no_prod++;
}

int main()
{
    int chkflg,i=0,flag=0,cflag=0;
    char ch;
    char input[1024];
    printf("..................\n");
    printf("..CASE  RIGISTER..\n");
    printf("..................\n");
    //strcpy(input,getinput(i+1));
    //printf("%s\n",input);
    do
    {
        strcpy(input,getinput(input));
        chkflg=check(input);
        switch(chkflg)
        {
            case 0:
                printf("Please Enter Correctly...!!!\n");
                printf("You Have entered Wrongly.!!!\n");
                flag=0;
                break;
            case 1:
                calc(input);
                flag=1;
                break;
            case 2:
                printf("You didnt enter anything.!!!\n");
                flag=0;
                break;  
            case 3:
                printf("Coundnot Subtract the Amount..!!!\n");
                flag = 0;
                break;      
        }
        if(flag == 0)
        {
            printf("Do u want to continue(y/n)");
            ch=getchar();
            if(ch == 'y')
            {
                flag=1;
                //continue;
            }
            else if(ch == 'n')
            {
                printf("Thank u..!!!\n");
                break;
            }
            else
            {
                printf("You didn't Enter Properly...!!!\n");
                break;
            }
        }   
    }while(flag == 1);
    print();
    return 0;
}

这是计算帐单的程序。该程序适用于正确的输入(例如double)。但问题是,如果我们输入错误的字符串,它会显示相应的情况,并询问是否继续。如果我们想继续,它会产生如下输出:

You Have entered Wrongly.!!!
Do u want to continue(y/n)y
Enter the Amount of the product 3:
You didn't enter anything.!!!
Do u want to continue(y/n)

它没有得到进一步的输入。我正在使用 gdb。但我不明白为什么它不能进一步得到输入。请帮我解决这个问题。提前谢谢你。

4

1 回答 1

2

当您使用getchar换行符时,您y在输入流中留下后按。然后,当您这样做时,gets它会读取该换行符并且您有一个空行。

解决此问题的一种方法是scanf在格式后使用例如空格,因为这会告诉scanf在读取字符后吃掉所有空格:

printf("Do you want to continue(y/n)");
scanf("%c ", &ch);

另一种解决方案是使用fgets读取整行,并使用例如提取答案sscanf

于 2013-01-17T13:27:04.377 回答