We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds first space.
There are 3 method by which C program accepts string with space in the form of user input.
Let we have a character array (string) named as str. So, we have declared a variable as char str
Method 1 : Using gets
Syntax : char *gets(char *str)
Note : gets() has been removed from c11. So it might give you a warning when implemented.
We see here that it doesn’t bothers about size of array. So, there is chance of Buffer Overflow.
Method 2 : To overcome above limitation, we can use fgets as :
Syntax : char *fgets(char *str, int size, FILE *stream)
Example : fgets(str, 20, stdin); as here, 20 is MAX_LIMIT according to declaration.
Method 3 : Using %[^\n]%*c inside scanf
Example : scanf(“%[^\n]%*c”, str);
Explanation : Here,  is the scanset character. ^\n tells to take input until newline doesn’t get encountered. Then, with this %*c, it reads newline character and here used * indicates that this newline character is discarded.
This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Different methods to reverse a string in C/C++
- Methods to concatenate string in C/C++ with Examples
- Hiding of all overloaded methods with same name in base class
- C++: Methods of code shortening in competitive programming
- Write a program that produces different results in C and C++
- Print 2D matrix in different lines and without curly braces in C/C++?
- Print colored message with different fonts and sizes in C
- Different ways to declare variable as constant in C and C++
- Linking Files having same variables with different data types in C
- Different ways to initialize a variable in C/C++
- Different ways to Initialize all members of an array to the same value in C
- Code valid in both C and C++ but produce different output
- Format specifiers in different Programming Languages
- How to use getline() in C++ when there are blank lines in input?
- getchar_unlocked() - faster input in C/C++ for Competitive Programming
- Clearing The Input Buffer In C/C++
- Inbuilt library functions for user Input | scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
- C | Input and Output | Question 13
- C | Input and Output | Question 2
- C | Input and Output | Question 3