首页 > 解决方案 > 如果输入“q”,则在 C 中创建一个退出的函数

问题描述

我必须编写一个没有参数并返回一个 int 值的函数。该函数要求用户输入“q”或“Q”以退出。如果输入任何其他字符,程序将继续。

标签: c

解决方案


像这样的东西...

#include <stdio.h>

char key;

int main()
{
    quitAtQ();
    return 0;
}

int quitAtQ() {
    int number = 1; // enter your return number here

    printf("Enter 'q' or 'Q' in order to quit\n");
    scanf_s("%c", &key);

    while ((strcmp("q", &key) != 0) && (strcmp("Q", &key) != 0)) {
        printf("You have entered char '%c', program continues\n", key);
        printf("Enter 'q' or 'Q' in order to quit\n");
        scanf_s("%c", &key); // enter key will be read as next char
        scanf_s("%c", &key); // next char input
    }
    return number;
}

推荐阅读