Remove \n after scanf() which read integer

后端 未结 2 1814
半阙折子戏
半阙折子戏 2021-01-21 06:29

I am raw and I wrote a lot of basic programs. There is something wrong in my new schedule program. I want to caltculate total park recipes and write on screen it with car number

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 06:59

    Standard C input functions only starts processing the input when you press the "Enter" key. Meanwhile, every key you press adds a character to a keyboard buffer.

    So basically when you use the scanf function, it does not read the buffer until the "Enter" key has been pressed.

    There are workarounds to pass this, but not with the standard C library.

    Cheers!

    Edit: The code below does not follow the standard C libraries. However, it does what you are asking for :)

    #include 
    #include 
    #include 
    
    double calculateCharges ( double time1 );
    
    int main( void )
    { //open main
    
        double time;
        int i,j = 0;
        double TotalCharges=0, TotalTime=0;
        char chTime[10];
    
    
        printf("Car\tHours\tCharge\t\n");
    
        for(i=1;i<=3;i++)   //there is 3 cars checkin
        {  //open for
    
            printf("%d\t",i);
    
            // Input the time
            j = 0;
            memset(chTime, '\0', 10);
    
            while ( 1 )
                {
                chTime[j] = getch();
    
                // User pressed "Enter"?
                if ( chTime[j] == 0x0d )
                {
                    chTime[j] = '\0';
                    break;
                }
    
                printf("%d", atoi(&chTime[j]));
                j++;
            }
    
            // Convert to the correct type
            time = atoi(&chTime[0]);
    
            TotalTime+=time;
    
            printf("\t%lf",calculateCharges(time) ); // fonks calculate
    
            TotalCharges+=calculateCharges(time);  // for total charge
    
            puts("");
    
            } // end for
    }  // end main
    
    double calculateCharges ( double time1 )
        {  //open fonk
    
            double totalC=0;
    
        if( time1<=3)       // untill 3 hours, for 2 dolars
        {   //open if
    
            totalC+=2.00;
    
        }   //end if
    
        else if(time1>3)      // after 3 hours, each hours cost 0.5 dolars
        {    //open else if
    
            totalC+=2+(time1-3)*0.5;
    
        }    //end else if
    
    
        return totalC;
    } // end fonk
    

提交回复
热议问题