在C中创建一个函数,如果输入“ q”,该函数将退出

时间:2018-06-28 22:19:35

标签: c

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

3 个答案:

答案 0 :(得分:0)

这是一种实现我认为你所说的方式的方法。

#include<stdio.h>
#include<stdlib.h> /* The library that is needed for the function exit() */
    int get_your_char(void);
    int main(void)
    {
            int x =get_your_char(); /* Here you call your function and you assign the returned integer to x */
            printf("%d",x);
            return 0;
    }
    int get_your_char(void)
    {
            char ch;
            int your_value=666; /* Let's assume that this is the value that you want to return if the user won't quit */
            ch=getchar(); /* Here you read the charachter */
            if(ch == 'q' || ch == 'Q')
                    exit(EXIT_SUCCESS); /* EXIT_SUCCESS usually is the value 0(zero) and makes the program terminate normally*/
            else
                    return your_value;
    }

答案 1 :(得分:0)

像这样...

#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;
}

答案 2 :(得分:0)

如果您希望根据返回值退出调用程序,则建议:

int user_wants_to_quit(void) {
    char input;
    printf("Enter 'q' to quit ");
    input = getchar();
    return input == 'q' || input == 'Q';
}

void caller() { // or main()

    // (...)

    if(user_wants_to_quit()) {
        exit(0); // 0 or whatever
    } else {
        puts("Let's continue then.");
    }

    // (...)

}