C: 你如何处理 scanf 没有用户输入的情况?

C: How do you handle for no user input for scanf?

亲爱的 Whosebugers,

你如何处理 0 个用户输入?

例如,如果用户输入“”或只是按回车键,您将如何处理?

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

int main() {

   printf("> \n");
   char string[129];
   int i = 0, length = 0, flag = 0;

   printf("Input a string: ");
   scanf("%128s", string);
   if(strlen(string) != 0) {
      printf("%s\n", string);
   } else {
      printf("Please enter at least one argument.");
   }
}

引用 C11,章节 §7.21.6.2,fscanf(),关于 %s 转换说明符,

s Matches a sequence of non-white-space characters.

以及关于执行转换说明符的步骤

Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.

因此,除非输入流中存在非空白字符,否则它将等待。 匹配不会发生。

此外,检查 scanf() 和 family 的 return 值以确保扫描成功非常重要。

也就是说,int main()至少应该是int main(void)才符合标准。

scanf() 实现这个可能是不可能的,我没有兴趣找出它是否可能,因为这个解决方案

#include <stdio.h> /* For fgets(), fprintf() and printf() */
#include <stdlib.h> /* For EXIT_FAILURE */
#include <ctype.h> /* For isspace() */

int
please_enter_at_least_one_argument()
{
    fprintf(stderr, "Please enter at least one argument\n");
    return EXIT_FAILURE;
}

int
main(void)
{
    char string[130];

    printf("> \n");
    printf("Input a string: ");
    if (fgets(string, sizeof(string), stdin) == NULL)
        return please_enter_at_least_one_argument();
    else
    {
        char *pointer;

        pointer = string;
        while (isspace((unsigned char) *pointer) != 0)
            pointer++;
        if (*pointer == '[=10=]')
            return please_enter_at_least_one_argument();
        printf("%s\n", string);
    }
    return 0;
}

解决问题,简单易懂

请注意,第一个 please_enter_at_least_one_argument() 可能不正确,因为如果您按 Ctrlfgets() 可能 return NULL +D (或在windows Ctrl+Z) 以及发生错误时。但要了解如何处理,您可能应该阅读 man fgets(3).