我有一个简单的C程序如下:
#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);
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");
}
}
当我执行以下程序时,将字符串读入 b 的 scanf 并没有等待我输入子字符串,而是在控制台上打印了打印 substring not found
的打印语句。我尝试给出 %s
并在 scanf 语句中尝试并从 printf 语句中删除 \n
并且没有任何改变它执行程序的方式。如果有人解决了这个简单的问题,那就太好了。提前致谢。
您可以使用 scanf ("%[^\n]%*c", variable);
使用此 scanf 将读取整行,而不是在到达空格时停止。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100];
char b[100];
char *ret;
printf("Enter the string\n");
scanf ("%[^\n]%*c", a);
printf("Enter the substring to be searched\n");
scanf ("%[^\n]%*c", b);
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
您也可以使用 fgets
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100];
char b[100];
char *ret;
printf("Enter the string\n");
fgets(a,100,stdin);//100 is the size of the string, you could use sizeof()
printf("Enter the substring to be searched\n");
fgets(b,100,stdin);//100 is the size of the string, you could use sizeof()
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}