【问题标题】:Why is scanf not allowing any more input?为什么 scanf 不允许更多输入?
【发布时间】:2017-01-29 12:46:17
【问题描述】:
#include <stdio.h>
#include <string.h>

int main() {
    char a[100], b[100];
    char *ret;
    scanf("%[^\n]s", a);
    scanf("%[^\n]s", b);
    ret = strstr(a, b);
    if (ret != NULL)
        printf("its a substring");
    else
        printf("not a substring");
    return 0;
}

我的目的是检查字符串中的父字符串中是否存在子字符串。我从here了解到strstr()函数。

我之前在我的代码中使用过%[^\n]s,它们运行良好。 但是,在这种情况下,只要我在输入一个字符串后按回车/回车,输出就是not a substring

我做错了什么?

【问题讨论】:

  • 试试scanf("%99[^\n]%*c", a); scanf("%99[^\n]", b);
  • 程序的输入是什么?预期和实际输出是多少?
  • 另外,如果您想阅读整行,我建议您使用fgets 而不是scanf
  • 为什么不直接使用scanf("%s", a);
  • @JithinPavithran 我想在我的字符串中有多个单词。 %s 不允许这样做。

标签: c scanf


【解决方案1】:

scanf() 的第一次调用在看到换行符 ('\n') 时停止,但它仍在输入流中。 因此,第二次调用立即失败,因为它看到(相同的)换行符。

您应该始终检查 scanf() 调用的返回值是否失败。

您可以在scanf() 调用之间插入getchar(); 调用以使用换行符。或者更好地使用fgets() 并处理换行符。


这就是您可以在代码中使用fgets() 的方式:

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

int main(void) {
     char a[100], b[100];
     char *ret;
     if (fgets(a, sizeof a, stdin) == NULL) {
        /* error handling */
     }

     a[strcspn(a, "\n")] = '\0';
     if (fgets(b, sizeof b, stdin) == NULL) {
       /* error handling */
     }

     b[strcspn(b, "\n")] = '\0';
     ret=strstr(a, b);
     if(ret!=NULL)
         printf("its a substring");
     else
         printf("not a substring");
     return 0; 
}

【讨论】:

  • 我正在使用 fgets() 来解决这个问题之前的字符串连接问题,但问题是连接之间还有一个换行符,所以我切换到了 scanf。跨度>
  • 另外,如何使用 getchar() 来消耗换行符?
  • fgets() 方法更好。您可以在ab 上调用fgets() 后使用strcspn(): a[strcspn(a, "\n")] = '\0';b[strcspn(b, "\n")] = '\0'; 将其删除。
  • 初学者有这个参考吗?很难理解:/
  • @Karan 他所说的基本上是retrieve a stringsearch for the newlineremove the newline
【解决方案2】:

您使用的scanf() 格式%[^\n] 没有尾随s,您应该提供要存储到目标数组中的最大字符数。由于数组的大小为 100,因此应指定 %99[^\n]

此外,您必须跳过 2 个 %99[^\n] 之间的换行符,否则第二次转换将失败,因为没有与 \n 不同的字符可以匹配。

这是使用scanf() 进行的简单更正。 usr 有一个很好的选择,使用 fgets(),这是一种更简单的解析输入的方法:

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

int main(void) {
    char a[100], b[100], c;

    if (scanf("%99[^\n]%c%99[^\n]", a, &c, b) == 3 && c == '\n') {
        if (strstr(a, b))
            printf("its a substring\n");
        else
            printf("not a substring\n");
    }
    return 0;
}

【讨论】:

  • 你能解释一下 %99[^\n] 部分吗?
  • 为什么要省略“s”(字符串的说明符)?
  • @KaranSingh:99 是要存储到指针参数指向的数组中的最大字符数(在空终止符之前,因此它是缓冲区大小 - 1)。跨度>
  • @KaranSingh:s 是一个错误:%s%[^\n] 是 2 个不同的转换说明符。使用您的格式字符串,scanf() 尝试在行尾匹配 s 并失败。
猜你喜欢
  • 2011-08-15
  • 1970-01-01
  • 2015-03-16
  • 2015-02-25
  • 2020-09-28
  • 2022-11-18
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多