如何读取字符指针与scanf的句子()?

问题描述 投票:-2回答:1

我有一个字符指针: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);没有工作。

我怎样才能做到这一点?

c string pointers scanf char-pointer
1个回答
1
投票

你是在声明变量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

© www.soinside.com 2019 - 2024. All rights reserved.