Reading String in C

Previous
Next

Reading string:

  • “%s” can be used to read a string.
  • “%s” will take the base address of memory block to read.
  • To read a string(more than 1 character), loops are not required.
#include<stdio.h>
int main()
{
	char name[20];
	
	printf("Enter your name : ");
	scanf("%s", name);
	
	printf("Hello %s, Welcome to Strings \n", name);
	return 0;
}
  1. Why we are not using loops to read and display strings?
  2. Why we are not specifying address to read the string?

Reading elements into array:

  • We must repeat loop to read elements into array.
  • We need to specify every location address to read the element of that location.
  • As we know the length of array to read elements, we can use loops.
  • We can read the string directly into array without using loops.
  • No need to specify the address of each location.
  • While reading elements into array, we can specify the number of element to input.
  • While reading the string, we cannot specify the number of character to input.
  • “%s” is a pre-defined program.
  • It 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.

Reading multi-word string:

  • gets() function can read multi word string.
  • It stops reading characters into array only when we hit “enter” key.
  • It reads Strings with spaces.
#include<stdio.h>
int main()
{
	char name[20];
	
	printf("Enter your name : ");
	gets(name);
	
	printf("Hello %s \n", name);
}

Display the String character by character:

#include<stdio.h>
int main()
{
	char name[20];
	int i;
	
	printf("Enter your name : ");
	gets(name);
	
	i=0;
	while(name[i] != '\0')
	{
		printf("%c \n", name[i]);
		i++;
	}
	return 0;
}
Previous
Next

Add Comment

Courses Enquiry Form