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;
and used scanf
to read input from the keyboard:
scanf("%s" , word) ;
but I got a segmentation fault.
How can I read input from the keyboard in C when the length is unknown ?
Note: The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to print and read strings directly.
Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.
C – Read String using Scanf() So, to read a string from console, give the format and argument to scanf() function as shown in the following code snippet. char name[30]; scanf("%s", name); Here, %s is the format to read a string and this string is stored in variable name .
Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.
You have no storage allocated for word
- it's just a dangling pointer.
Change:
char * word;
to:
char word[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.
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);
I cannot see why there is a recommendation to use scanf()
here. scanf()
is safe only if you add restriction parameters to the format string - such as %64s
or so.
A much better way is to use 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 } }
(untested)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With