【问题标题】:Why isn't my %[^\n] not working properly? [duplicate]为什么我的 %[^\n] 不能正常工作? [复制]
【发布时间】:2017-09-19 14:01:09
【问题描述】:
int main() {
    char a[100];

    printf("\nEnter 1st Sentence : ");
    scanf("%[^\n]", a);
    printf("\nSentence 1 : %s", a);

    printf("\nEnter 2nd Sentence : ");
    scanf("%[^\n]", a);
    printf("\nSentence 2 : %s", a);

    return 0;
}

我的输出:

Enter 1st Sentence : Testing 1st Sentence
Sentence 1 : Testing 1st Sentence
Enter 2nd Sentence : 
Sentence 2 : Testing 1st Sentence

我基本上是在检查 %[^\n]。当我输入第 1 个句子并按“Enter”键时,它会打印“Enter 2nd Sentence:”,然后是“Sentence 2:”,然后它会打印第 1 个句子。

【问题讨论】:

标签: c


【解决方案1】:

因为您没有从输入缓冲区中读取 Enter 键,所以当第二个 scanf() 要求输入时,它仍然存在。然后它认为你只是按了 Enter 键而没有输入任何文本。

【讨论】:

    【解决方案2】:

    用这个代替scanf("%[^\n]", a)

    fgets(a, sizeof(a), stdin);
    

    还有just strip the trailing newline你自己。

    【讨论】:

      【解决方案3】:

      scanf("%[^\n]", a)存在多个问题:

      • 如果读取长度超过 99 个字节的行,您可能会出现缓冲区溢出。您可以使用scanf("%99[^\n]", a) 来防止这种情况发生。

      • 您将换行符保留在输入流中,并且它仍然存在于下一次调用中,这会导致转换失败,因为格式必须匹配至少一个与换行符不同的字节。您可以通过使用scanf(" %[^\n]", a) 忽略前导空格来防止这种情况。注意格式字符串中的初始空格。

      • 您不检查转换是否成功。 scanf() 返回成功转换的次数。在您的情况下,它应该返回 1

      这是修改后的程序:

      #include <stdio.h>
      
      int main(void) {
          char a[100];
      
          printf("\nEnter 1st Sentence: ");
          if (scanf(" %99[^\n]", a) != 1)
              return 1;
          printf("\nSentence 1 : %s", a);
      
          printf("\nEnter 2nd Sentence : ");
          if (scanf(" %99[^\n]", a) != 1)
              return 1;
          printf("\nSentence 2 : %s", a);
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-22
        • 1970-01-01
        • 2012-06-12
        • 2019-08-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 2021-09-25
        • 2023-04-07
        相关资源
        最近更新 更多