scanf无法读取C

时间:2018-05-05 15:46:56

标签: 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");
  }
}

当我执行以下程序时,scanf将字符串读入b不等待我输入子字符串,打印substring not found的print语句正在控制台上打印。我尝试给%s并尝试使用scanf语句并从printf语句中删除\n,并且没有改变它执行程序的方式。如果有人解决这个简单的问题会很棒。提前谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用此scanf ("%[^\n]%*c", variable);来扫描整行,而不是在达到空格时停止。

#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");
  }
}

答案 1 :(得分:2)

尝试使用fgets代替scanf,原因可能是空格被视为分隔符,空格前的部分被视为a而后部分被视为b该空间将被视为Firestore。因此,该程序没有提示您进行其他输入。

获取您的信息:Reading string from input with space character?