【问题标题】:Hitting return terminates 2 scanf("%[^\n]%*c")击中返回终止 2 scanf("%[^\n]%*c")
【发布时间】:2019-09-20 18:46:54
【问题描述】:

我正在尝试读取 2 行用户输入。对于第一个序列,如果我不输入任何内容并按回车键,程序将打印enter the second sequence,但不允许第二个scanf。基本上返回只是终止scanf,导致str1str2 都为空。

printf("enter the first sequence: ");
scanf("%[^\n]%*c", str1);

printf("enter the second sequence: ");
scanf("%[^\n]%*c", str2);

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: c string scanf c99


    【解决方案1】:

    字符串的格式说明符是%s,所以请改用它:

    printf("enter the first sequence: ");
    scanf("\n%s", str1);
    
    printf("enter the second sequence: ");
    scanf("\n%s", str2);
    

    正如@AjayBrahmakshatriya 评论的那样:\n 匹配任意数量的\n 字符。

    %c 在使用 scanf 读取 char 时的问题在于它将换行符视为输入,正如我在此 example 中解释的那样。


    但是,如果我是你,我只会使用fgets(),就像这样:

    fgets(str1, sizeof(str1), stdin);
    fgets(str2, sizeof(str2), stdin);
    

    如果您采用这种方法,那么您可能会对Removing trailing newline character from fgets() input 感兴趣?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多