正确清除键盘缓冲区

时间:2014-02-27 20:55:15

标签: c

我正在尝试为我的计算类做一个问题而我遇到了麻烦。问题是一条长度需要从河的左侧向右侧行驶长度的渡轮,我相信有人之前已经听说过它。我唯一的问题(我很好的想法如何做大部分代码,只是遇到障碍)是我要么陷入无限循环,要么我的嵌套循环退出for循环它嵌套在最底部附近。我的代码如下:

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

int main(int argc, char* argv[])
{
int testCases;
int ferrySize;
int numOfCars;
char riverSide; // what side of river is the car on?
char c; // eats unnecessary characters
int test=1;
int i,j=0;// counters for "for" and "while" loops
int carLength;
const int cm_to_m=100;

printf("How many tests would you like to have?: ");
scanf("%d", &testCases);
printf("how long is the ferry in meters and how many cars are there?: ");
scanf("%d", &ferrySize);
ferrySize=ferrySize*cm_to_m;
scanf("%d", &numOfCars);
printf("cases %d ferrysize %d cars %d\n", testCases, ferrySize, numOfCars);
printf("\nhow long is each car (in cm) and what side is it on?\n(seperate this info with a space)\nseperate each car by new lines.");


for(i=0; i<=numOfCars;i++);
{
    scanf("%d", &carLength);
    scanf(" %c", &riverSide);
    printf("%c", riverSide);
    do
    {
        scanf("%c", &c);
        printf("%c", c);
    }while(c!='t' && c!='T');
    printf("%c", riverSide);

}
return 0;

}

2 个答案:

答案 0 :(得分:0)

尝试使用fflush(),它将清空缓冲区并且代码运行正常。

答案 1 :(得分:0)

检查for循环行末尾的额外分号。您还可以在循环中执行以下操作来读取值(忽略安全性等):

for(i=0; i<numOfCars; i++) {
    scanf("%d %c", &carLength, &riverSide);
    printf("car is %d long and on the %c side\n", carLength, riverSide");
}