如何使用C从键盘读取字符串?

时间:2011-10-10 07:00:33

标签: c string scanf

我想读取用户输入的字符串。我不知道字符串的长度。由于C中没有字符串,我声明了一个指针:

char * word;

并使用scanf从键盘读取输入:

scanf("%s" , word) ;

但是我遇到了分段错误。

当长度未知时,如何从C中读取键盘输入?

5 个答案:

答案 0 :(得分:50)

您没有为word分配存储空间 - 它只是dangling pointer

变化:

char * word;

为:

char word[256];

请注意,256是一个任意选择 - 此缓冲区的大小需要大于您可能遇到的最大可能字符串。

另请注意,fgets是一个更好(更安全)的选项,然后scanf用于读取任意长度的字符串,因为它需要一个size参数,这反过来有助于防止缓冲区溢出:

 fgets(word, sizeof(word), stdin);

答案 1 :(得分:17)

我不明白为什么有人建议在这里使用scanf()。仅当您将限制参数添加到格式字符串时,scanf()才是安全的 - 例如%64s左右。

更好的方法是使用char * fgets ( char * str, int num, FILE * stream );

int main()
{
    char data[64];
    if (fgets(data, sizeof data, stdin)) {
        // input has worked, do something with data
    }
}

(未测试的)

答案 2 :(得分:15)

当从任何不知道长度的文件(包含stdin)读取输入时,通常最好使用getline而不是scanffgets,因为{{1}只要提供一个空指针来接收输入的字符串,就会自动处理字符串的内存分配。这个例子将说明:

getline

相关部分是:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    ssize_t read;

    printf ("\nEnter string below [ctrl + d] to quit\n");

    while ((read = getline(&line, &len, stdin)) != -1) {

        if (read > 0)
            printf ("\n  read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

        printf ("Enter string below [ctrl + d] to quit\n");
    }

    free (line);  /* free memory allocated by getline */

    return 0;
}

char *line = NULL; /* forces getline to allocate with malloc */ size_t len = 0; /* ignored when line = NULL */ /* snip */ read = getline (&line, &len, stdin); 设置为line会导致getline自动分配内存。示例输出:

NULL

因此,对于$ ./getline_example Enter string below [ctrl + d] to quit A short string to test getline! read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline! Enter string below [ctrl + d] to quit A little bit longer string to show that getline will allocated again without resetting line = NULL read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL Enter string below [ctrl + d] to quit ,您无需猜测用户字符串的长度。

答案 3 :(得分:1)

你需要指针指向某个地方才能使用它。

试试这段代码:

char word[64];
scanf("%s", word);

这会创建一个lenth 64的字符数组并读取它的输入。请注意,如果输入超过64个字节,则字数组溢出,程序变得不可靠。

正如Jens指出的那样,最好不要使用scanf来读取字符串。这将是安全的解决方案。

char word[64]
fgets(word, 63, stdin);
word[63] = 0;

答案 4 :(得分:0)

以下代码可用于从用户读取输入字符串。但是它的空间限制为64。

char word[64] = { '\0' };  //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
    scanf_s("%c", &word[i++], 1);
}