【问题标题】:Problem while using scanf("%19[^\n]",Input) in C在 C 中使用 scanf("%19[^\n]",Input) 时出现问题
【发布时间】:2020-05-03 12:11:32
【问题描述】:

所以基本上当我使用 scanf("%19[^\n]", Input);我的输出有问题。

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

    void inputTime();

    int main()
    {
        int test = 0;
       do
       {
         inputTime();
         test++;
       } while (test!=2);

       return 0;
    }
    void inputTime()
    {

       char Input[20];
         printf("Test : ");
          *Input = '\0';
          scanf("%19[^\n]", Input);
    }

在我的 char[] 的第一次输入之后,程序和 [^\n] 不能让我输出两次。 这是我在输出中得到的:

测试:SomeString 测试://无法输入第二个字符串 进程返回 0 (0x0) 执行时间:11.599 s 按任意键继续。

但是,如果我将 scanf("%19[^\n]", Input) 更改为 scanf("%19s", Input) 它可以正常工作

测试:SomeString Test : AnotherString //现在可以在这里写了 进程返回 0 (0x0) 执行时间:11.599 s 按任意键继续。

如何在使用 scanf("%19[^\n]", Input) 时获得相同的结果?

【问题讨论】:

    标签: c


    【解决方案1】:

    "在我的 char[] 的第一次输入之后,程序和 [^\n] 不能让我输出两次。但是,如果我将 scanf("%19[^\n]", Input) 更改为 scanf("%19s", Input) 它可以正常工作。 "

    这是因为%[ 中的转换说明符:

    scanf("%19[^\n]", Input);
    

    与转换说明符 %s 相反,不会跳过前导空白字符,例如在上一次调用中的前一次调用中,在stdin 中留下的 Return 中的 \n(换行符) main 中循环的迭代。

    %[之前添加一个空白字符指令:

    scanf(" %19[^\n]", Input);
    

    或在前面插入一个getchar() 调用来捕捉左边的newline

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 2013-03-04
      相关资源
      最近更新 更多