2014-02-27 131 views
0

我想为我的计算机课程做一个问题,但我遇到了麻烦。问题在于长度需要从小河的左边到右边的长度的渡轮,我确信有人听说过它。我唯一的问题(我有一个好主意如何做大部分代码,只是碰到了一个障碍)是我要么陷入一个无限循环,要么我的嵌套循环退出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; 

}

+1

对于扫描字符,请使用'的getchar()',而不是'的scanf( “%C”,... )'。 'scanf()'在扫描字符方面很差。 –

+0

我的教授出于某种原因教导我们使用scanf代替。我认为他希望我们由于某种原因而忽略空白字符?另外,我尝试了getchar函数,以便它可以修复它 - 它具有与scanf相同的效果。退出程序(尽管不会崩溃),好像它已经完成了所有的事情,尽管for循环仍然应该运行。 – msd94

+0

你能给出一个样本输入和期望的输出吗? – emsworth

回答

0

尝试使用fflush(),它会清空缓冲区和代码将运行得很好。

+0

缓冲区的文件是标准输入吗?我会试试看。谢谢 – msd94

+0

如果你不给它任何参数,它会刷新一切。试试这种方式。 – homa

+0

它仍然退出所有循环。我要猜测我的for循环出现了问题...编辑:我发现了问题!这是我的循环,检查条件...(...; ...; ...);而不是(...; ...; ...) – msd94

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"); 
}