简体   繁体   English

格式说明符C ++有什么问题

[英]What is the problem with the format specifier C++

I have the following code: 我有以下代码:

#include <cstdio>

int main()
{
    float b = 323.23f;
    std::scanf("%6.3f\n", &b);  // <-- Warning
    std::printf("%6.3f\n", b);
}

There is a warning at scanf() stating: scanf()有一个警告说明:

Invalid conversion specifier '.' 无效的转化说明符'.'

Is there something I am missing here? 这里有什么我想念的吗?

When you use %6.3f with printf , the .3 specifies the precision of the output. %6.3fprintf.3指定输出的精度。

scanf doesn't need you to specify the precision, because it will accept whatever precision it finds in the input stream. scanf不需要您指定精度,因为它将接受它在输入流中找到的任何精度。 So you aren't allowed to specify .3 (or . -anything-else) in a scanf format. 因此,您不能以scanf格式指定.3 (或. -anything-else)。 Just use %6f or even %f instead. 只需使用%6f甚至%f

The format specifier for scanf doesn't require you to explicitly specify the number of places after the decimal point. scanf的格式说明符不要求您明确指定小数点后的位数。 Plus, it is what is causing the warning, it is better off to use just a plain %f inside the scanf though a %6f also works. 另外,它是引起警告的原因,最好只使用scanf的普通%f ,尽管%6f也可以。

This isn't the case with the printf though. 但是, printf的情况并非如此。 When you use a [some_number].[number_of_places]f , like, for example, 6.3f in a printf , while the .3f would affect the number of places after the decimal point which would be displayed, the 6 in it reserves that many character spaces to display the entire number. 当您使用[some_number].[number_of_places]f ,例如,在printf中使用6.3f ,而.3f会影响将显示的小数点后面的位数,其中的6将保留许多字符空格显示整个数字。

Hope this helps to some extent. 希望这在一定程度上有所帮助。

The format specifier in C does not take the value '6.3'.You can use '%6f' or simply '%f'. C中的格式说明符不取值“6.3”。您可以使用'%6f'或简单地'%f'。 '%6.3f' is the thing that is causing the warning. '%6.3f'是导致警告的事情。

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

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