我正在创建一个简单的应用程序来跟踪我工作的时间。用户输入他们正在进行的工作分钟数,程序将跟踪总数,直到终止。问题是在程序第一次运行它之后打印出它的第一个语句两次。我把它放在一个无限循环中,我对scanf和printf没有很好的掌握,所以我认为这就是我的失败所在。任何帮助将不胜感激。
这就是程序的样子:
#include <stdlib.h>
#include <stdio.h>
void logic(int *minutesWorked, int *hoursWorked, int *totalMinutesWorked);
int main(void)
{
int minutesWorked = 0;
int hoursWorked = 0;
char letter = 0;
int totalMinutesWorked = 0;
while (1) {
printf("Enter I for input or T for total\n");
scanf("%c", &letter);
if (letter == 'i' || letter == 'I') {
printf("Please enter minutes worked\n");
scanf("%d", &minutesWorked);
logic(&minutesWorked, &hoursWorked, &totalMinutesWorked);
}
else if (letter == 't' || letter == 'T') {
printf("Hours worked is %d and minutes worked is %d\n", hoursWorked,totalMinutesWorked);
}
}
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
void logic(int *minutesWorked, int *hoursWorked, int *totalMinutesWorked)
{
*totalMinutesWorked += *minutesWorked;
if (*totalMinutesWorked >= 60) {
*hoursWorked += *totalMinutesWorked / 60;
*totalMinutesWorked = *totalMinutesWorked % 60;
}
} /* ----- end of function logic ----- */
这是它显示的一个例子:
Enter I for input or T for total
I
Please enter minutes worked
100
Enter I for input or T for total
Enter I for input or T for total
I
Please enter minutes worked
33
Enter I for input or T for total
Enter I for input or T for total
T
Hours worked is 2 and minutes worked is 13
Enter I for input or T for total
Enter I for input or T for total
答案 0 :(得分:1)
最好的解决方案是使用fgets()而不是scanf(),但如果这不是一个选项,你可以在每次scanf调用后添加这一行来清除输入缓冲区:
fseek(stdin, 0, SEEK_END);