Using comma before format spec. in scanf in C?

Viewed 55

I have a function like this:

void getCommands( int commands[][ 2 ] )
{ 
   int i, tempCommand;
   
   printf( "Enter command ( 9 to end input ): " );
   scanf( "%d", &tempCommand );
   
   for ( i = 0; tempCommand != 9 && i < MAX; i++ )
   { 
      commands[ i ][ 0 ] = tempCommand;

      if ( tempCommand == 5 )
         scanf( ",%d", &commands[ i ][ 1 ] );
        
      printf( "Enter command ( 9 to end input ): " );
      scanf( "%d", &tempCommand );
    }

   commands[ i ][ 0 ] = 9;
   
 }

My question is what the ",%d" means in:

    if ( tempCommand == 5 )
        scanf( ",%d", &commands[ i ][ 1 ] ); 

What I'm trying to say is how does that comma before %d work?

You can actually see from the code below exactly what I mean (type 5,12 in reponse to the first prompt, for example).

#include <stdio.h>
int main()
{
    int a,b=0;
    scanf("%d",&a);
    printf("%d %d\n",a,b);
    scanf(",%d",&b);
    printf("%d %d",a,b);
}
1 Answers

The comma (or any other non-whitespace character not preceded by the % format specifier) signals that any such identical character in the input stream is 'skipped' (i.e. consumed but not used); if a matching comma is not found, the scanf call fails.

From cppreference:

non-whitespace multibyte characters except %: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.

So, in your example, when 5,12 is given as input, the first scanf call extracts the 5 value (into a) then the next call skips the , and reads the 12 into b (using the %d format).

Related