Strings in C

Strings in C


In C, we don't have any string data type directly.
But, we know that any string is collection of characters. So, we can define any string as collection of character array.

There are few points to be noted while handling string:

  • We have to  use %s as format specifier and not %c.
  • String ends with \0.
  • If we use scanf() function then we need not write & operator for storing value in particular variable. (see example below)
  • If we use %s in scanf() function then only characters upto space will be considered. So, we use gets() function.


Let's see this program for clarification:


#include<stdio.h>
void main()
{
char a[10];
printf("Enter string: ");
scanf("%s",a);
printf("\nEntered string is: %s",a);
}

Output:


Note: Only Hello is printed and not Hello Hi

So, as shown in above program and screenshots, 
  • We have used %s as format specifier and not %c.
  • Also if we use scanf we get only characters till space is encountered. 


So, to overcome this problem we use gets() function.
Let's see program below:

#include<stdio.h>

void main()
{
char a[10];
printf("Enter string: ");
gets(a);
printf("\nEntered string is: %s",a);
}

Output:





Thus, we get desired output if we use gets() function.

No comments:

Post a Comment