Google Add

Search

How to Read a String with Spaces in C

How to read a string with spaces in C.  In C program scanf only read word until it encounters whitespace. So how to read a complete string. This is the common problem faced by beginners when try to input space separated string.

How to Read a String with Spaces in C


Let's see what happens when you read string using scanf. Here is a simple program to demostrate what happens with scanf when you try to read string using string format specifier(%s).

Programming questions on strings

Sorting algo and their time complexity



#include <stdio.h>

void main()
{
    char str[100];
    
    printf("Enter a string");
    scanf("%s",str);
    
    
    printf("Enter string is %s",str);

}


Output

Enter a string :  I am learning programming

Enter string is :  I

You can see that scanf method reads only first word. It reads a word until it encounters whitespace.


Let's do some modification

How to Read a String with Spaces using Scanf in C


#include <stdio.h>

void main()
{
    char str[100];
    
    printf("Enter a string");
    scanf("%[^\n]",str);
    
    
    printf("Enter string is %s",str);

}

Output

Enter a string : I am learning programming


Enter string is :  I am learning programming

Read a String in C using gets()


#include <stdio.h>

int main(void) {
 
 char str[100];
 
 printf("Enter a string \n");
 gets(str);
 
 printf("\n Enter string is %s", str);
 return 0;
}


Reverse a string using stack.

No comments:

Post a Comment