C语言中scanf读取子字符串时未等待输入的问题求助
输入缓冲区残留字符导致
scanf跳过输入的解决方案 嘿,这个问题我太熟了!你的第二个scanf直接跳过输入,根源是输入缓冲区里残留的字符在捣乱,我给你拆解下原因和解决办法:
问题根源
当你用第一个scanf("%s", a)读取字符串时,它只会读取到**第一个空白字符(空格、换行、制表符)**就停止。常见两种触发场景:
- 如果你输入
test然后按回车,scanf会把test存入a,但回车产生的\n会留在输入缓冲区里; - 如果你输入
hello world这种带空格的字符串,scanf只会把hello存入a,剩下的world\n全留在缓冲区里。
不管是哪种情况,第二个scanf("%s", b)执行时,要么直接读取缓冲区里的残留内容,要么跳过换行后误以为已经完成输入,导致你觉得程序没等你输入就继续执行了。
三种解决办法
方法1:手动清空输入缓冲区
在第一个scanf之后,用循环把缓冲区里的所有残留字符(直到换行符)都清空:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char a[100],b[100]; char *ret; printf("Enter the string\n"); scanf("%s",a); // 清空缓冲区直到遇到换行 while(getchar() != '\n'); printf("Enter the substring to be searched\n"); scanf("%s",b); ret= strstr(a,b); if(ret==NULL) { printf("Substring not found\n"); } else { printf("Substring found \n"); } return 0; }
方法2:给scanf格式串加前导空格
在%s前面加一个空格,让scanf自动跳过所有前导空白字符(包括换行、空格、制表符):
// 注意%符号前的空格 scanf(" %s", b);
这个方法简单快捷,但只解决了换行/空格残留的问题,如果第一个输入带空格,第二个scanf还是会读取空格后的内容。
方法3:用fgets替代scanf(更推荐)
scanf("%s")天生无法读取带空格的字符串,而fgets可以读取整行输入,还能自动处理换行符,是更安全的选择:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char a[100],b[100]; char *ret; printf("Enter the string\n"); fgets(a, sizeof(a), stdin); // 去掉fgets读取到的换行符 a[strcspn(a, "\n")] = '\0'; printf("Enter the substring to be searched\n"); fgets(b, sizeof(b), stdin); b[strcspn(b, "\n")] = '\0'; ret= strstr(a,b); if(ret==NULL) { printf("Substring not found\n"); } else { printf("Substring found \n"); } return 0; }
这里strcspn(a, "\n")会找到字符串中换行符的位置,把它替换成字符串结束符\0,避免换行符影响后续的strstr查找。
内容的提问来源于stack exchange,提问作者user8540390
相关产品推荐
相关产品推荐

