Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf() skip variable

Tags:

In C, using scanf() with the parameters, scanf("%d %*d", &a, &b) acts differently. It enters value for just one variable not two!

Please explain this!

scanf("%d %*d", &a, &b); 
like image 509
ross Avatar asked Sep 30 '11 07:09

ross


People also ask

How do I skip scanf?

If we want to skip any data from assigning into variables in the scanf() function in C programming language, then we can use the asterisk ( * ) symbol right after the percent ( % ) symbol in the scanf() function. So, we can do that by simply adding an asterisk * after the % .

Is scanf %d safe?

For example, when reading an int : int i; scanf("%d", &i); the above cannot be used safely in case of an overflow. Even for the first case, reading a string is much more simpler to do with fgets rather than with scanf .

Why %d is used in scanf?

The “%d” in scanf allows the function to recognise user input as being of an integer data type, which matches the data type of our variable number. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.


2 Answers

The * basically means the specifier is ignored (integer is read, but not assigned).

Quotation from man scanf:

 *        Suppresses assignment.  The conversion that follows occurs as           usual, but no pointer is used; the result of the conversion is           simply discarded. 
like image 127
jpalecek Avatar answered Jan 11 '23 19:01

jpalecek


Asterisk (*) means that the value for format will be read but won't be written into variable. scanf doesn't expect variable pointer in its parameter list for this value. You should write:

scanf("%d %*d",&a); 
like image 44
Tomek Szpakowicz Avatar answered Jan 11 '23 17:01

Tomek Szpakowicz