如何使用scanf从输入中仅获取一个字符?

时间:2019-10-24 16:20:35

标签: c char scanf

我已经解决了在char之前按'enter'的问题,但还有一件事。这是我来自Visual Studio的代码:

 #include <stdio.h>



int main() {
    char ch, yn;
    printf("Enter a character: ");
    scanf(" %c", &ch);
    printf("You entered -> %c\n", ch);
    printf("Continue? [y/n]: ");
    scanf(" %c", &yn);
    if (yn == 'y' || yn == 'Y') {
        while (ch != 'q' && ch != 'Q') {
            printf("---------------------------------\n");
            printf("Enter another character ([q]uit): ");
            scanf(" %c", &ch);
            printf("You entered -> %c\n", ch);
        }
    }
    else if (yn == 'n' || yn == 'N') {
        exit(0);
    }
    else {
        printf("\n-- Invalid character! --\a\n\n");
    }
    return 0;
}

因此,如果用户输入的内容类似于“ abc ”而不是“ a ”,则“ b ”代表“ 继续” ?”的问题。并出现代码中的错误消息。那是我的问题,我应该写什么才能只读取第一个字符?

1 个答案:

答案 0 :(得分:0)

fgets可用于读取单个字符。测试换行符以查看是否输入了太多字符,并根据需要重新提示。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int fgetschar ( char *choice, FILE *fin);

int main ( void) {
    char ch, yn;
    printf("Enter a character: ");
    if ( fgetschar ( &ch, stdin)) {
        printf("You entered -> %c\n", ch);
    }
    else {
        exit ( 0);
    }
    printf("Continue? [y/n]: ");
    if ( fgetschar ( &yn, stdin)) {
        if (yn == 'y' || yn == 'Y') {
            while (ch != 'q' && ch != 'Q') {
                printf("---------------------------------\n");
                printf("Enter another character ([q]uit): ");
                if ( fgetschar ( &ch, stdin)) {
                    printf("You entered -> %c\n", ch);
                }
                else {
                    exit ( 0);
                }
            }
        }
        else if (yn == 'n' || yn == 'N') {
            exit(0);
        }
        else {
            printf("\n-- Invalid character! --\a\n\n");
        }
    }
    else {
        exit ( 0);
    }
    return 0;
}

int fgetschar ( char *choice, FILE *fin) {
    char input[100] = "";

    do {
        if ( input[0] == '\x01') {
            printf ( "\tToo many characters. Try again.\n\n");
        }
        printf ( "Enter one character: ");
        fflush ( stdout);//force print since printf does not have newline
        if ( fgets ( input, 3, fin)) {
            if ( !strchr ( input, '\n')) {//no newline
                while ( !strchr ( input, '\n')) {//call until newline is found to clear input
                    if ( !fgets ( input, sizeof input, fin)) {
                        fprintf ( stderr, "\nfgets problem\n");
                        *choice = 0;
                        return 0;
                    }
                }
                input[0] = '\x01';//unlikely to be a valid character
            }
        }
        else {
            fprintf ( stderr, "\nfgets problem\n");
            *choice = 0;
            return 0;
        }
    } while ( input[0] == '\x01');

    *choice = input[0];

    return 1;
}