c - 此代码中的 scanf 输入问题

标签 c loops io scanf

我还是C语言的初学者。这段代码接受输入

s 10
w 5
s 20
w 10

其中 s 是行程时间,w 是等待时间。

然后它根据旅行时间和等待时间以及声明为全局变量的票价计算总账单。

此代码未正确接受 while 循环中的输入。有人可以告诉我为什么会这样吗?如果可以在此代码中进行任何改进,我们也将不胜感激。

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


struct bill
{
  int travelTime;
  int waitTime;

  float cost;

};

typedef struct bill BILL;

BILL *bill1;



int BASEFARE = 10; // in Rupees
int TRAVELFARE = 1; //in Rupees
float WAITFARE = 0.1; // in Rupees


int main()
{

    int choice = 1;

    bill1 = (BILL*)malloc(sizeof(BILL));

    bill1->travelTime = 0;
    bill1->waitTime = 0;

    while(choice)
    {
        char state = ' ';
        int period = 0;
        printf("Enter  state\n");
        //scanf("%c %d",&state,&period);
        scanf("%c %d",&state, &period);



        if(state == 's')
        {
            bill1->travelTime = bill1->travelTime + period;
        }
        else if(state == 'w')
        {
            bill1->waitTime = bill1->waitTime + period;
        }
        else if(state == 'e')
        {
            printf("\nTotal TravelTime is %d s ",bill1->travelTime);
            printf("\nTotal WaitTime is %d s", bill1->waitTime);

            bill1->cost = BASEFARE + (bill1->travelTime * TRAVELFARE) + (bill1->waitTime * WAITFARE);

            choice = 0;
        }
        else
        {
            printf("\nError in data format please ReEnter data\n");
            free(bill1);
            choice = 0;
        }
    }

    printf("\nThe Final bill is %f", bill1->cost);

return 0;
}
 OUTPUT
    ________________
    Enter  state
    s 10
    Enter  state
    w 5 

    Error in data format please ReEnter data

    The Final bill is 0.000000

最佳答案

改变这个:

scanf("%c %d", &state, &period);

为此:

scanf(" %c %d", &state, &period);

格式字符串中的空格匹配输入中的 0 个或多个空格字符。


附言:malloc()stdlib.h 中声明.

“malloc.h”不是标准头文件,所以它不应该像#include<malloc.h>。 .如果是自定义 header ,应该用双引号括起来,像这样:#include "malloc.h" .如果您没有名为“malloc.h”的自定义 header ,请丢弃此包含。


与您的问题无关,但Do I cast the result of malloc?没有。

关于c - 此代码中的 scanf 输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391631/

相关文章:

javascript - 循环遍历数组,但即使 “else” 语句为 true 也执行 “if” 语句 (javascript)

javascript - 使用 For 循环初始化 JQuery Accordion

mysql - node.js - 代码执行路径的精度

c - "extra"分号是什么意思?

c - 如何使用我的字符串将 "interleave"C/C++ 源代码(仅在适当位置的内部函数中)?

c - 停止计算欧几里德算法的 C 程序中的运行时错误

c - 从文本文件中读取并将行解析为 C 中的单词

Java - Zip 到文件目录问题

c - 程序终止后变量保留值,如何防止? C

c - 在 ncurses 中打印盲文字符