简体   繁体   English

C 中的 scanf() 中的格式化字符串

[英]Formatted string in scanf() in C

Just like printf() , I was trying to use optional specifiers in scanf() format string.就像printf()一样,我试图在scanf()格式字符串中使用可选说明符。 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() ?现在在printf()中,它只是根据这些说明符保留列并打印,但是scanf()会发生什么? Like what is meaning of %3d and %3.3f here?就像这里的%3d%3.3f是什么意思? Is this even relevant in case of scanf() ?这在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 )由于您在评论中指定您真正想知道的是'如果我强行尝试这样做会怎样'......这是结果(使用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. a"%d"被正确存储。
  2. Regardless of what value is entered, the " %3.3f " for b always stores 0.000000无论输入什么值, b" %3.3f "总是存储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 !自己试试看吧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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