Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read string from keyboard using C?

Tags:

c

string

scanf

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 ?

like image 732
mainajaved Avatar asked Oct 10 '11 07:10

mainajaved


People also ask

Can you print a string in C?

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.

How do you find a letter in a string C?

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.

How do I read a string in scanf?

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 .

Is there a type string in C?

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.


2 Answers

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); 
like image 85
Paul R Avatar answered Sep 23 '22 03:09

Paul R


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)

like image 31
glglgl Avatar answered Sep 20 '22 03:09

glglgl