The power of scanf()

This tip submitted by Joanna on 2006-12-20 01:54:31. It has been viewed 46958 times.
Rating of 7.0 with 342 votes



Assume we have: char a[100];

To read a string:
scanf("%[^\n]\n", a);
// it means read until you meet '\n', then trash that '\n'


To read till a coma:
scanf("%[^,]", a);
// this one doesn't trash the coma


scanf("%[^,],",a);
// this one trashes the coma


If you want to skip some input, use * sign after %. For example you want to read last name from "John Smith" :

scanf("%s %s", temp, last_name);
// typical answer, using 1 temporary variable

scanf("%s", last_name);
scanf("%s", last_name);
// another answer, only use 1 variable, but calls scanf twice

scanf("%*s %s", last);
// best answer, because you don't need extra temporary variable nor calling scanf twice


By the way, you should be very careful with using scanf because of the potential to overflow your input buffer! Generally you should consider using fgets and sscanf rather than just scanf itself, using fgets to read in a line and then sscanf to parse that line as demonstrated above.



More tips

Help your fellow programmers! Add a tip!