如何检查输入是否为空?

问题描述 投票:0回答:1

如何检查用户是否没有输入任何内容,只按了回车键?如果发生这种情况,则错误消息和代码将停止。用C语言写的。

我尝试了

== '\n'
" "
但没有任何效果:(

int main() {
    int number;
    printf("Number 1-8: ");
    if (scanf("%d", &number) != 1 || number < 1 || number > 8 || number == '\n') {
        printf("error");
        return 1;
    }
    return 0;
}
c stdin
1个回答
5
投票

scanf
说明符
%d
将消耗所有1前导空格,其中包括换行符(换行符)。

不要使用

scanf
,而是使用
fgets
将整行读入数组。然后用这些数据做任何你需要做的事情。

空字符串是以空终止字节开头的字符串。

sscanf
可用于解析字符串,类似于
scanf
解析标准输入的方式。

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

int main(void)
{
    char line[512];

    while (1) {
        printf("Enter a value between 1 - 8: ");

        if (!fgets(line, sizeof line, stdin)) {
            if (ferror(stdin))
                perror("stdin");
            break;
        }

        /* remove trailing new line character */
        line[strcspn(line, "\n")] = '\0';

        /* an empty line - first character is the null-terminating byte */
        if (!line[0]) {
            fputs("You entered nothing! Try again.\n", stderr);
            continue;
        }

        /* allow the user to exit the prompt */
        if (0 == strcmp(line, ".exit"))
            break;

        int value;

        if (1 == sscanf(line, "%d", &value)) {
            if (1 <= value && value <= 8) {
                printf("Got valid value: <%d>\n", value);
            } else {
                printf("Value <%d> out of range.\n", value);
            }
        } else {
            fprintf(stderr, "Could not parse number from <%s>\n", line);
        }
    }
}
Enter a value between 1 - 8: 
You entered nothing! Try again.
Enter a value between 1 - 8: 7
Got valid value: <7>
Enter a value between 1 - 8: 123
Value <123> out of range.
Enter a value between 1 - 8: foobar
Could not parse number from <foobar>
Enter a value between 1 - 8: .exit

另请参阅:从 fgets() 输入中删除尾随换行符

1。假设没有发生错误。

© www.soinside.com 2019 - 2024. All rights reserved.