在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);
}
答案 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);