将用户输入存储在变量中,以便我可以从中获取子字符串

时间:2015-12-15 15:40:01

标签: c

在C编程中,如何将用户输入存储在变量中,以便从中获取子字符串? 输入" hello Point"在控制台中我收到一个错误:子字符串是NULL。这意味着我的word变量是空的?究竟我做错了什么以及为什么?

#include <stdio.h>
#include <string.h>


int main()
{
   char word[100];

   printf ("Enter a word: ");
   scanf ("%s", word);
   const char needle[] = "Point";
   char *ret;

   ret = strstr(word, needle);

   printf("The substring is: %s\n", ret);
   return(0);
}

2 个答案:

答案 0 :(得分:3)

%s的{​​{1}}在找到空格时停止阅读。

请尝试使用scanf()。 (添加scanf ("%99[^\n]", word);以避免缓冲区溢出)

答案 1 :(得分:2)

如果找不到子字符串,

strstr将返回NULL。这就是这种情况。您正在使用scanf来读取字符串。它会在第一次出现空格后停止扫描,此处为' '。因此,只有hello将存储在word中,而strstr(word, needle)将返回NULL

使用fgets代替读取字符串。

fgets(word, sizeof(word), stdin);
相关问题