25

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);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
ross
  • 388
  • 2
  • 4
  • 10

4 Answers4

33

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.
jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • But what happened if I discard an integer that actually does not exists on the file, it seems that fscanf does not fail. – Bionix1441 Oct 05 '17 at 15:01
17

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);
Tomek Szpakowicz
  • 14,063
  • 3
  • 33
  • 55
  • Is there a way to ignore all the characters after the one that we want to read using `fscanf`? i.e ignore everything until the end of the line? I have been looking for that for quite some time. – Bionix1441 Sep 20 '17 at 10:21
  • @Bionix1441 `scanf` reads only as much characters from `stdin` (and `fscanf` from file) as is needed to satisfy the format string. If you are getting incorrect values in your variables this means that you get an error matching the format. Check the return value. If it does not help, I guess you need to post a proper question with examples. – Tomek Szpakowicz Sep 21 '17 at 17:41
3

http://en.wikipedia.org/wiki/Scanf#Format_string_specifications

An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable.

reader_1000
  • 2,473
  • 17
  • 15
-2

The key here is to clear the buffer, so scanf will not think that it already has some input, and so it will not get skipped!

#include <stdio.h>
#include<stdlib.h>

void main() {
    char operator;
    double n1, n2;

    printf("Enter two operands: ");
    scanf("%lf %lf",&n1, &n2);
    
   fflush(stdin);   //do this between two scanf
    
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);

}

fflush(stdin); //this clears the scanf for new input so it does not ignore any input taking line becuase it has some charater already stored in its memory