一个简单的程序有点奇怪,可能是scanf问题

时间:2010-11-08 21:06:05

标签: c scanf

我有一个简单的功课......制作一个3个值3次的C程序

  1. 食物的id(char)
  2. 食物的卡路价值(浮动)
  3. 食物量(浮子)
  4. 以下是程序给我的代码和输出:

    #include <stdio.h>
    #define NUM_OF_FOOD 3
    
    int main()
    {
        float food_cal[NUM_OF_FOOD];
        float food_amount[NUM_OF_FOOD];
        char food_id[NUM_OF_FOOD];
        int i;
        float total_cal=0;
        int most_fat_food_id=0;
        printf("enter the following data: food ID, Cal value and Amount eaten \nexample A 10 3\n");
        for (i=0;i<NUM_OF_FOOD;i++)
        {
            printf("\nEnter product #%d:",i);
            int inputLength = scanf("%c %f %f",&food_id[i],&food_cal[i],&food_amount[i]);
            if ( inputLength < 3 ) {
                printf("input error, input length was %d excpexted 3", inputLength);
                break;
            }
            if ( !((food_id[i]>96 && food_id[i]<123) || (food_id[i]>64 && food_id[i]<91)) ) {
                 printf("ID input error");
                 break;
            }
            if ( food_cal[i] < 0 ) {
                printf("Food Cal input error");
                break;
            }
            if ( food_amount[i] < 0 ) {
                printf("Food Amount input error");
                break;
            }
            printf("\n%c %5.2f %5.2f",food_id[i],food_cal[i],food_amount[i]);
        }
        for (i=0;i<NUM_OF_FOOD;i++)
            total_cal+=food_cal[i]*food_amount[i];
    
        printf ("\nTotal amount of calories is %5.2f\n",total_cal);
        for (i=1;i<NUM_OF_FOOD;i++)
             most_fat_food_id = (food_cal[most_fat_food_id]<food_cal[i]) ? i : most_fat_food_id;
    
        printf ("\nThe most fattening product is: %c with %5.2f calories",food_id[most_fat_food_id],food_cal[most_fat_food_id]);
    
        return 0;
    }
    
    /*
    enter the following data: food ID, Cal value and Amount eaten 
    example A 10 3
    
    Enter product #0:A 1000 2
    
    A 1000.00  2.00
    Enter product #1:B 500 3
    input error, input length was 1 excpexted 3
    Total amount of calories is 2000.00
    
    The most fattening product is: A with 1000.00 calories
    */
    

    它只是跳过第3次

    的输入

    不知道为什么......两个人看着代码,看起来很好,但仍然有错误。

3 个答案:

答案 0 :(得分:1)

输入:A 1000 2 [ENTER] B 500 3 [ENTER] ...

第一个scanf("%c %f %f")读取'A',1000和2并在[ENTER]处停止

第二个scanf("%c %f %f")读取[ENTER]并与B一起扼流“%f”转换。

您可以尝试使用scanf(" %c %f %f")强制跳过可选空格,然后再读取字符。

答案 1 :(得分:0)

您不使用'\ n'

快速/脏的方法是添加一个变量:

char readNewLine;

scanf()之后,添加另一个:

scanf("%c", &readNewLine);

这很难看,但它就足够了 - 在你使用C一段时间后,更好的方法将可用。

答案 2 :(得分:0)

第33行后

添加:

char nl = 0;
scanf("%c", &nl);

将消耗最终的换行符,这会搞砸了。

在上述建议之后,这是输出:

./test
enter the following data: food ID, Cal value and Amount eaten
example A 10 3

Enter product #0:a 10 2

a 10.00  2.00
Enter product #1:b 3 29

b  3.00 29.00
Enter product #2:c 32 4

c 32.00  4.00
Total amount of calories is 235.00

The most fattening product is: c with 32.00 calories