C – Reading Strings

Program to read and display string:

int main()
{
            char name[20];
            printf(“Enter your name : “);
            scanf(“%s”, name);
           
            printf(“Hello %s, Welcome to Strings \n”, name);
            return 0;
}

How %s read input into String variable:

  • “%s” takes the base address of memory block.
  • It reads character by character and stores from the base address.
  • Once input is over, it will add null character at the end of the string.

Program to read multi-word string in C:

  • gets() function can read a string with multiple spaces.
  • It stops reading characters into array only when we hit “enter” key.
int main()
{
            char name[20];
            printf(“Enter multi word name : “);
            gets(name);
            printf(“Hello %s \n”, name);
}

Scroll to Top