简体   繁体   中英

Formatted string in scanf() in C

Just like printf() , I was trying to use optional specifiers in scanf() format string. I tried to use the width and precision specifier. Now in printf() it simply reserves the columns and print according to these specifiers but what happens with scanf() ? Like what is meaning of %3d and %3.3f here? Is this even relevant in case of scanf() ? I have a little idea that width in this case represents the number of characters that are to be read for some particular format but not sure. Below code explains this further:

#include<stdio.h>
int main()
{
int a;
float b;
printf("Enter Numbers:\n");
scanf("%3d %3.3f",&a,&b);
printf("Entered Numbers are\n");
printf("%d %f",a,b);
return 0;
}

Since you specified in the comments that what you really want to know is ' what if i forcefully try to do it '... Here are the results (with Clang )

warning: invalid conversion specifier '.'

and

warning: data argument not used by format string

The program compiles, however, since these are just warnings.

Upon executing the binary, and entering the variables asked for:

  1. The "%d" for a gets stored properly.
  2. Regardless of what value is entered, the " %3.3f " for b always stores 0.000000

In short, the it does what almost any other code that compiles with warnings does - not behave as intended . This is neither undefined, nor unspecified behaviour, but it is wrong .

Suggestion: Refrain from asking questions that are of the nature ' what happens if I try to compile this '. Just try and see for yourself !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM