调用(是/否)函数以确定用户是否输入有效输入

我试图调用是/否函数来查看用户是否输入了有效输入,在这种情况下是’Y””N”n’。 但是我不希望输出之间有两条新线,你可以从下面的附图看到。

部件不正确

clearKeyboard函数:void clearKeyboard(void)

{ int c; while ((c = getchar()) != '\n' && c != EOF); } 

是/否function:

 int yes(void) { int result, done = 1; char c = 0, charenter; scanf("%c%c", &charenter, &c); while (done == 1) { if (c != '\n' || (!(charenter == 'Y' || charenter == 'y' || charenter == 'N' || charenter == 'n'))) { clearKeyboard(); printf("*** INVALID ENTRY *** : "); scanf("%c%c", &charenter, &c); } else { done = 0; } } if (charenter == 'Y' || charenter == 'y') result = 1; else if (charenter == 'N' || charenter == 'n') result = 0; return result; } 

调用yes / no函数的函数:我试过删除fflush(stdin); 或者在%c之前留一个空格,没有一个工作。 但“家庭电话号码”部分工作正常,没有给我新行/输入错误无效。

 void getNumbers(struct Numbers *numbers) // getNumbers function definition { char answer; int result; printf("Please enter the contact's cell phone number: "); scanf("%s", numbers->cell); printf("Do you want to enter a home phone number? (y or n): "); scanf("%c", &answer); result = yes(); while (result == 1) { printf("Please enter the contact's home phone number: "); scanf("%s", numbers->home); break; } printf("Do you want to enter a business phone number? (y or n): "); fflush(stdin); scanf("%c", &answer); result = yes(); while (result == 1) { printf("Please enter the contact's business phone number: "); scanf("%s", numbers->business); break; } } 

提前致谢!

我建议使用fgets代替scanf ,你可以使用fgets更多地控制线条。

如果你使用scanf来读取字符串,我会使用这个函数来清除缓冲区:

 void clear_buffer(FILE *fp) { int c; while((c=fgetc(fp)) != '\n' && c!=EOF); } 

然后你就可以做到

 char name[15]; char phone[15]; scanf("%14s", name); clear_buffer(stdin); scanf("%14s", phone); clear_buffer(stdin); 

所以你的yes函数可以重写为:

 int yes(const char *prompt) { char line[10]; int ret; do { printf("%s: ", prompt); fflush(stdout); ret = scanf("%9s", line); clear_buffer(stdin); if(ret == 1) { // catch entries like "yes" and "nooooooo" if(line[1] != 0) line[0] = 0; switch(line[0]) { case 'y': case 'Y': return 1; case 'n': case 'N': return 0; default: printf("*** INVALID ENTRY *** \n"); } } } while(ret != EOF); return 0; } 

那么你可以读这样的数字:

 void getNumbers(struct Numbers *numbers) // getNumbers function definition { int result; printf("Please enter the contact's cell phone number: "); scanf("%s", numbers->cell); clear_buffer(stdin); if(yes("Do you want to enter a home phone number? (y or n)")) { printf("Please enter the contact's home phone number: "); scanf("%s", numbers->home); clear_buffer(stdin); } if(yes("Do you want to enter a business phone number? (y or n)")) { printf("Please enter the contact's business phone number: "); scanf("%s", numbers->business); clear_buffer(stdin); } } 

顺便问一下:你为什么要这样做

 while (result == 1) { printf("Please enter the contact's home phone number: "); scanf("%s", numbers->home); break; } 

代替

 if (result == 1) { printf("Please enter the contact's home phone number: "); scanf("%s", numbers->home); } 

这产生了相同的结果,但这更容易阅读。