ss_blog_claim=726e70d7c87c20ae33aa7a61f06eb8aa

Friday, November 28, 2008

The usage of ‘gets’ statement in C Programming

Well we have already discussed about the usage of ‘fflush’ statement, let us now discuss about the usage of ‘gets’ statement. String is an array of characters and we use the format specifier ‘%s’ to directly get these array of characters, which is not possible in the case of array of integers. In the case of array of integers we use the ‘for’ loop to get the values since we don't have any format specifier for array of integers.

To get array of characters we use the format specifier ‘%s’ as shown below

puts(“Enter the string”);
scanf(“%s”,ex_str);
puts(ex_str);

Output:

Enter a string
sample text
sample

What is wrong in the output?? We know that ‘Space’ and ‘Enter’ key act as a delimiter. So if you execute this program and give input as ‘sample text’ the value stored in ‘ex_str’ is ‘sample’ and not ‘sample text’ this is because the space in between the words ‘sample’ and ‘text’ acts as a delimiter thus storing only ‘sample’ in the character array (string). To overcome this problem we use the ‘gets’ statement. The ‘gets’ statement takes only the ‘Enter’ key as delimiter. The below part of the code shows how to use ‘gets’ statement.

puts(“Enter a string”);
gets(ex_str);
puts(ex_str);

Output:

Enter a string
sample text

sample text

Just think of getting a name of a person which contains first name, last name and middle name so this ‘gets’ statement is much useful in those situations. Happy Programming!!

No comments: