How to properly use the * text modifier in a printf statement.

I amin a beginning C programming class. While writing a simple program I had to tell a scanf statement to ignore the leading white space:

scanf(" %c" . &char);

I read in the textbook that the * is used as a more general form that would ignore any data type that was in the buffer. There were example programs showing its use. However, when I tried to use the astrix the program would not function. It compiled and ran, but it treated the statement as if the astrix was not even there.

scanf("*%c". &char);

So, did I do something wrong? Is this particular to only some compilers?

Woops, I screwed up in the title. I meant to say scanf statement.

I have taught beginning C (although in a corporate rather than academic setting) and am not familiar with the * formatting feature. I wonder if it’s ANSI.

I would use getchar for what you’re trying to do.

(Using %c is the only time scanf does not skip past white space.)

P.S. “asterisk”

An asterisk may be used following the percent sign to suppress assignment for that match. In other words, saying “%*c” would say, “match what you normally would for %c, but don’t assign it to anything.”

I think you likely would want to use the following (untested, but documented in Kernighan and Ritchie):


scanf ("%1s", &myChar);

This specifier will skip whitespace as it’s expecting a string (which ignores whitespace) but the field width is set to 1, so only a single character is read from the input stream.
The * modifier is used to ignore a particular input in the stream (in the case of scanf), and it must be between the % and the conversion specifier. So if someone entered three integers separated by spaces but you only wanted the third integer, you could use:


scanf("%*d %*d %d, &thirdInt);

I also find that some scanf docs which appear to say that if you precede the “c” conversion specifier with a space, the scanf statement will ignore leading whitespace. This may be an implementation difference.
If you only want a character, you might also consider using the getchar() function:


char myInput;
while ( (myInput = getchar ()) != '
' )
{
    /* if input is white space, toss it */
}

Example from man(3C) scanf(), Solaris 5.8:

int i; float x; char name[50];
(void) scanf("%2d%f%*d %[0123456789]", &i, &x, name);

 with input:

 56789 0123 56a72

 will assign 56 to i, 789.0 to x, skip 123,  and  place  the string  56\0  in  name.  The  next  call to getchar(3C) will return the character a.

-lv