在scanf()之后删除\ n,读取整数

我是生的,我写了很多基本的程序。 我的新计划程序有问题。 我想要计算整个公园食谱并在屏幕上写上车号和小时数。 此序列必须是Car Hours Charge。 在我的程序中,只有scanf()向用户询问小时。用户写入小时并输入,程序获取新行。我想要像这样输出

Car Hours Charge 1 5 3.00 

但程序输出就像

 Car Hours Charge 1 5 3.00 

这是我的程序源代码:

 #include double calculateCharges ( double time1 ); int main( void ) { //open main double time; int i; double TotalCharges=0, TotalTime=0; printf("Car\tHours\tCharge\t\n"); for(i=1;i<=3;i++) //there is 3 cars checkin { //open for printf("%d\t",i); scanf("%lf", &time); printf("\t"); TotalTime+=time; printf("%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( time13) // 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 

据我所知,这是一个与终端相关的“问题”。 当您在终端中键入内容时,输入不会发送到程序,直到您按Enter键并输入将添加新行。

您需要做的是更改终端行为,以便您键入的所有内容立即发送到程序。

看看这个问题,最佳答案将告诉你如何做你想做的事: 如何避免按任何getchar()输入

标准C输入function仅在您按“Enter”键时开始处理输入。 同时,您按下的每个键都会在键盘缓冲区中添加一个字符。

所以基本上当你使用scanf函数时,它不会读取缓冲区,直到按下“Enter”键。

有一些解决方法可以通过它,但不能使用标准C库。

干杯!

编辑:下面的代码不遵循标准C库。 但是,它做你要求的:)

 #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