为什么scanf不允许再输入?

Kar*_*ngh 9 c scanf

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的目的是检查字符串中父字符串中是否存在子字符串.我strstr()这里了解了这个功能.

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

我做错了什么?

usr*_*usr 13

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

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

您可以在getchar();调用之间插入一个scanf()调用来使用换行符.或者更好地使用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; 
}
Run Code Online (Sandbox Code Playgroud)