主要修改部分是函数文件中的get_first()函数
- 将其中的
ch = getchar();
改为scanf(" %c", &ch);
注意,为了获得第一个非空字符,在%c前添加了空格让scanf函数忽略%c前的所有空白。- 将函数拆分为三个文件,便于整理与修改
- 因使用CLion编写,头文件会稍有不同,不必在意
主函数main.c
#include <stdio.h>
#include "choiceAndGet.h"
int main() {
int choice;
while ((choice = get_choice()) != 'q') { // 当不退出时
switch (choice) {
case 'a':
printf("Buy low, sell high!\n");
break;
case 'b':
printf("蜂鸣声\n");
break;
case 'c':
count();
break;
default:
printf("输入错误!\n");
break;
}
}
printf("Bye!\n");
return 0;
}
头文件choiceAndGet.h
#ifndef PRO01_CHOICEANDGET_H
#define PRO01_CHOICEANDGET_H
int get_choice(void ); // 获取输入的选项
void count(void ); // 数数函数
int get_first(void ); // 获取第一个字符
int get_int(void ); // 获取第一个int
#endif //PRO01_CHOICEANDGET_H
函数文件choiceAndGet.c
#include <stdio.h>
#include "choiceAndGet.h"
int get_choice(void ) {
/*
* 显示选项
* 获取用户响应
* 如果相应不合适
* 提示用户再次输入
* 获取用户响应
*/
int ch;
printf("Enter the letter of your choice:\n");
printf("a. advice b. bell\n");
printf("c. count q. quit\n");
ch = get_first();
while ((ch < 'a' || ch > 'c') && ch != 'q') {
printf("Please respond with a, b, c, or q.\n");
ch = get_first();
}
return ch;
}
int get_first(void ) { // 获取第一个非空输入并删掉后续所有字符直到'\n'
int ch;
scanf(" %c", &ch); // 在%c前加上空格以省略前面的空白来获取第一个char(此时获取到的char不会是换行,空格,制表符)
while (getchar() != '\n')
continue;
return ch;
}
void count(void ) {
int n, i;
printf("Count how far? Enter an integer:\n");
n = get_int();
for (i = 1; i <= n; i++) {
printf("%d\n", i);
}
while (getchar() != '\n')
continue;
}
int get_int(void ) {
int input;
char ch;
while (scanf("%d", &input) != 1) {
while ((ch = getchar()) != '\n') {
putchar(ch);
}
printf(" is not an integer.\nPlease enter an integer like 1, -3, or 3:");
}
return input;
}