Taking String input with space in C (3 Different Methods)

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[20]



Method 1 : Using gets

Syntax : char *gets(char *str)

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int main()
{
   char str[20];
   gets(str);
   printf("%s", str);
   return 0;
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
#define MAX_LIMIT 20
int main()
{
   char str[MAX_LIMIT];
   fgets(str, MAX_LIMIT, stdin);
   printf("%s", str);
  
   return 0;
}

chevron_right


 

Method 3 : Using %[^\n]%*c inside scanf

Example : scanf(“%[^\n]%*c”, str);

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int main()
{
   char str[20];
   scanf("%[^\n]%*c", str);
   printf("%s", str);
  
   return 0;
}

chevron_right


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 contribute@geeksforgeeks.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.



My Personal Notes arrow_drop_up

Improved By : SagarPandita, ankush_953



Article Tags :
Practice Tags :


8


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.