我有一个字符指针:char *sentences;
和我读它是这样的:
#include <stdio.h>
int main() {
char *sentences;
sentences="We test coders. Give us a try?";
printf("%s", sentences);
return 0;
}
但我想在C scanf()
函数读取。
scanf("%[^\n]s",S);
或scanf("%s",S);
没有工作。
我怎样才能做到这一点?
你是在声明变量char *sentences;
并立即试图写它scanf
?这是行不通的。
除非char *
指针指向现有的字符串,或与malloc
家庭功能分配的内存,与scanf
或类似分配给它是未定义的行为:
char *sentences;
scanf("%s", sentences); // sentences is a dangling pointer - UB
既然你还没有真正分享你的代码,使用scanf
并不起作用,我只能假设这就是问题所在。
如果要分配一个用户提供的值成一个字符串,你可以做的是将其声明为固定长度的阵列,然后用合适的输入功能读取它。 scanf
将工作如果正确使用,但fgets
是简单的:
char sentence[200];
fgets(sentence, 200, stdin);
// (User inputs "We test coders. Give us a try")
printf("%s", sentence);
// Output: We test coders. Give us a try.
此外,永远,永远使用gets
。