#1 Printing the string containing Blank spaces while using Scanf
Problem: While using scanf for getting a string we have the limitation of string upto blank space.As soon as blank spaces occurs in a string scanf terminates to take that input.
i.e .
char line[80];
char line[80];
scanf("%s",line);
for above program if we type
India is my country.
then line[ ] be assigned only "India"
Solution:
To solve this problem we could use a conversion process.
Actually the "%s " in scanf converts our input to some string terminated with \0. As soon as the \0 occurs it does not take input. So following the rule of type conversion we can instruct our compiler to take input according to our own way.
An alternative method to print a string containing white space chararcter and uppercase character is that , write all uppercase letters including white sapce should be added in a square bracket in place of s, So that our compiler could interpret them and read them.
scanf (" %[ ABCDEFGHIJKLMNOPQRSTUWXYZ]", line ) ;
Now if our input is
INDIA IS MY COUNTRY.
then line will be assigned the whole string "INDIA IS MY COUNTRY"
but now since we have not added the lowercase character hence as soon as it recognizes the lowercase letter it will terminate the scanning process.
Obviously , we could add lowercase character as well, but it will become cumbersome for us to write all those we want.
Now seeing the above solution, it comes to our mind that the above solution could be better if we could make compiler interpret the above things in opposite manner.i.e. what I mean to say that there should be some instruction , applying which we could help to ignore those characters which we are writing in code.
Because the ignored characters will be lesser than the used ones.
So ans is yes , we could use a circumflex (^)before our letters to be interpreted in opposite manner.
thus for ignoroing \n
the code will be simply like this :
scanf("%[^\n]",line);
No comments:
Post a Comment