【问题标题】:scanf fails to read a string in C [duplicate]scanf 无法读取 C 中的字符串 [重复]
【发布时间】:2018-05-05 15:46:56
【问题描述】:

我有一个简单的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 并没有改变它执行程序的方式。如果有人能解决这个简单的问题,那就太好了。提前致谢。

【问题讨论】:

  • 显示您的输入,第一个是否包含空格? %s 格式说明符在第一个空白字符处停止。
  • scanf() 不接受带有空格的字符串。
  • 我在你的代码中没有发现任何错误。它在 gcc 中对我来说很好用。尝试 ` printf("\nEnter the string");` 和 printf("\nEnter the substring to be searched"); 。使用 \n 之前。
  • 你可以在这里找到答案:stackoverflow.com/questions/6282198/…
  • 如果我输入 hi how are you 作为我的主字符串输入,则存在问题,并且第二个 scanf 没有等待输入,并且正在打印 atlast substring not found。好像我输入heyyyyyyyyyyyy作为我的主要字符串输入,第二个scanf正在等待我输入子字符串,我输入eyyy,结果是找到子字符串。

标签: c printf scanf


【解决方案1】:

您可以使用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");
  }
}

【讨论】:

  • 应该是%99[^\n]%*c 以防止缓冲区溢出。
【解决方案2】:

尝试使用fgets而不是scanf,可能原因是空格被视为分隔符,空格之前的部分被视为a,而空格之后的部分将被视为b。因此程序没有提示您输入其他内容。

供您参考:Reading string from input with space character?

【讨论】:

  • 是fgets还是gets?
  • 查看提供的信息,有说明没有使用gets。 fgets 和 gets 是不同的。
猜你喜欢
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 2021-02-27
相关资源
最近更新 更多