Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds the first space. 
There are 4 methods by which the C program accepts a string with space in the form of user input.
Let us have a character array (string) named str[]. So, we have declared a variable as char str[20].

Method 1 : Using gets
Syntax : char *gets(char *str)

C

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

                    

Note : gets() has been removed from c11. So it might give you a warning when implemented. 
We see here that it doesn’t bother about the size of the array. So, there is a chance of Buffer Overflow.

Method 2 : To overcome the 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.

C

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

                    

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

C

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

                    

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.


 

Method 4 :  Using %[^\n]s inside scanf.

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

C

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

                    

Explanation : Here, [] is the scanset character. ^\n tells to take input until newline doesn’t get encountered. Here we used ^ (XOR -Operator ) which gives true until both characters are different. Once the character is equal to New-line (‘\n’),  ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);

This article is contributed by Mukesh patel.



Last Updated : 22 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads