如何使用C从键盘读取字符串? [英] How to read string from keyboard using C?
问题描述
我想读取用户输入的字符串.我不知道字符串的长度.由于C中没有字符串,所以我声明了一个指针:
I want to read a string entered by the user. I don't know the length of the string. As there are no strings in C I declared a pointer:
char * word;
并使用 scanf
从键盘读取输入:
and used scanf
to read input from the keyboard:
scanf("%s" , word) ;
但是我遇到了细分错误.
but I got a segmentation fault.
当长度未知时,如何在C中从键盘读取输入?
How can I read input from the keyboard in C when the length is unknown ?
推荐答案
You have no storage allocated for word
- it's just a dangling pointer.
更改:
char * word;
收件人:
char word[256];
请注意,这里的256是一个任意选择-该缓冲区的大小必须大于您可能遇到的最大字符串.
Note that 256 is an arbitrary choice here - the size of this buffer needs to be greater than the largest possible string that you might encounter.
还请注意,与 scanf 用于读取任意长度的字符串,因为它采用了 size
参数,该参数反过来有助于防止缓冲区溢出:
Note also that fgets is a better (safer) option then scanf for reading arbitrary length strings, in that it takes a size
argument, which in turn helps to prevent buffer overflows:
fgets(word, sizeof(word), stdin);
这篇关于如何使用C从键盘读取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!