格式化输入的问题
本帖最后由 梦回连营 于 2021-9-10 10:47 编辑#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define MAX_NUM 100
int generate_num(void);
int guess_num(int);
int main(void)
{
int ans, contin, guess;
char control;
contin = true;
while (contin){
ans = generate_num();
guess = guess_num(ans);
printf("the num you guess is %d, \nbut the ans is %d\n", guess, ans);
printf("do you want continue(y/n): ");
scanf("%c", &control);
if (control == 'y')
continue;
else
break;
}
printf("123%c123\n", control);
printf("the game is over\n");
return 0;
}
int generate_num(void){
srand((unsigned) time(NULL));
return rand() % MAX_NUM + 1;
}
int guess_num(int answer){
int guess;
printf("guess a num: ");
scanf("%d", &guess);
return guess;
}
运行结果如图所示。我的输入‘y/n’控制循环这一步直接被跳过了,我试验后发现是在第一步猜一个数的输入的时候是按了一个数字和回车键,第二个输入的时候继续处理了我的回车键,导致程序直接跳出了,怎么样才能避免这种情况发生呢???? 在两次输入之间加一个 getchar()
用它来接受回车键
加一个 getchar();
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define MAX_NUM 100
int generate_num(void);
int guess_num(int);
int main(void)
{
int ans, contin, guess;
char control;
contin = true;
while (contin){
ans = generate_num();
guess = guess_num(ans);
printf("the num you guess is %d, \nbut the ans is %d\n", guess, ans);
printf("do you want continue(y/n): ");
scanf("%c", &control);
if (control == 'y')
continue;
else
break;
}
printf("123%c123\n", control);
printf("the game is over\n");
return 0;
}
int generate_num(void){
srand((unsigned) time(NULL));
return rand() % (MAX_NUM) + 1;
}
int guess_num(int answer){
int guess;
printf("guess a num: ");
scanf("%d", &guess);
getchar();
return guess;
}
人造人 发表于 2021-9-10 10:50
加一个 getchar();
谢谢你的回答,明白了
页:
[1]