c - scanf 无法读取 C 中的字符串

标签 c printf scanf

<分区>

我有一个简单的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");
  }
}

关于c - scanf 无法读取 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191249/

相关文章:

c - 在 C 中,如何将 scanf 的分隔符设置为非字母的任何内容?

c - fscanf() 在读取文件上的结构时只能接受一个字符串,而不是 int C

c - 将动态数组传递给c中的函数

c++ - 找到debugging printf去掉

java - 关于创建非标准大小的字节组的非常简单的问题

c - 为什么 swap(&a++,&b++) 给出错误 "invalid lvalue in unary ' &'"?

c - 打印 union 值的怪癖

c - 为什么我的最终 scanf 不停止并读取用户输入?

c - 如何在 C 中提取 32 位无符号整数的特定 'n' 位?

c++ - 如何将 C/C++ 库代码封装为可在具有多个实例的单独线程中运行?