《C Primer Plus》Page238 程序清单8.8 部分重写

主要修改部分是函数文件中的get_first()函数

  1. 将其中的 ch = getchar();改为scanf(" %c", &ch);注意,为了获得第一个非空字符在%c前添加了空格让scanf函数忽略%c前的所有空白。
  2. 将函数拆分为三个文件,便于整理与修改
  3. 因使用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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值