January 13, 2015

Things you don't know about scanf()

19:28 Posted by Durga swaroop Perla No comments
Scanf() is an inbuilt function in the C Standard libraries. This is used to get input from the user and store that in a variable.
scanf provides inbuilt mechanisms to tackle with de-limiters which many people are not aware of. So, today we'll show you how you can limit your input till a certain symbol.

Consider we have a variable declared as
char a[20];
Reading a String:
To read a string usually we use '%S'. Instead of that we can also use the following way to get the value till you encounter '\n' and discard it.
scanf("%[^\n]\n",a);
This only stores the value till '\n' is encountered and discards it.
To read till a Comma:
Just like the above scenario we will use comma (,) as our delimiter. That would be,
scanf("%[^,],"a);
This will read till the , is encountered and discards everything after it.

Other Delimiters:
Just like above, you will replace the comma (,) with your required delimiter and use it just like that.
so, for example lets say you want to stop reading after a hyphen (-), then you will sue the following.
scanf("%[^-]-",a);
Skipping an input at run time:
Sometimes its possible that you want to have one value in your variable even though the user is going to enter multiple for the same.
An, example would be where the user wants to enter his name and you are only interested in his/her last name.
Then you would want to store only the last name by skipping the first name like this, by using a "*", after the "%".
scanf("%*s %s",a);
So, That is all for this article. If you like this article you might like our other articles too about Programming. So, check them out. Also stay tuned for a lot of other interesting articles.

As, always, Have a happy reading and Stay Awesome !

-------------------------------------------------------------------------------------------------
Follow our blog posts @ Follow. So that you won't miss any interesting post and also to be the first to know the answers to many interesting questions.
Follow us on our Facebook  page @ Fre Blogg 
Head over to my You Tube channel for some interesting tutorials @ You Tube

About the author :

Durga Swaroop is a Blogger, Freelance Video Editor, Tech Enthusiast, Philanthropist and a BITSIAN at heart. He is currently working as a Networking Enginner at Ericsson R & D. You can contact him through the following social networks.

0 comments:

Post a Comment

Please Enter your comment here......