【问题标题】:Data argument not used by format string - Outputting long格式字符串未使用数据参数 - 输出长
【发布时间】:2017-07-21 15:49:15
【问题描述】:

好的,这是一个 C 程序......即使我把它放在正确的位置,我也会遇到这个问题。长毫秒,在打印中我有“l”。现在,x 是一个全局 int 变量,用户通过命令行参数输入 x 然后 atoi() 参数。

这个问题发生在一个函数中。我想知道我是否输出错误。在尝试输出之前将 int x 设置为这个 long ms 变量时,我应该进行类型转换还是什么?我很困惑并试图输出毫秒数。

    struct timespec now;
 clock_gettime(CLOCK_REALTIME, &now);
 long ms;
 x = ms;
 ms = round(now.tv_nsec / 1.0e6);

 fprintf(stdout, "l: flip\n", ms);

【问题讨论】:

  • fprintf(stdout, "l: flip\n", ms); 看起来不对。您忘记添加格式说明符%ld
  • 警告:无效的转换说明符 ':' [-Wformat-invalid-specifier] fprintf(stdout, "%l: flip\n", ms);
  • 谢谢,但它仍然会出现类似反转转换说明符的问题。
  • 使用%ld 而不是%l
  • 谢谢。是的,嗯,至少现在它给了我一些数字……现在我必须让它更好地工作。伟大的!所以这个类型转换问题就解决了。多谢你们!我可以继续工作以完成我的计划。 :)

标签: c timer arguments real-time clock


【解决方案1】:

我已经用我看到的东西评论了你的代码。

struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
long ms;
x = ms;  
// <== this is assigning a variable 'ms' to the variable 'x'
// however, the variable 'ms' is not initialized 
// this will cause the compiler to raise a warning message
// about using an uninitialized variable
// this is (for the above reason) undefined behavior

ms = round(now.tv_nsec / 1.0e6); 
// <-- initialized the variable 'ms'
// but it is too late for the prior statement
// AND the compiler will not be happy about the 'implied' 
// conversion from the returned type from 'round()' 
// which is 'double' to the type 'long int' of the variable 'ms'
// The compiler will be happy if the line is written like this:
ms = (long int)round( now.tv_nsec / 1.0e6 );


fprintf(stdout, "l: flip\n", ms); 
// <-- will cause the compiler to complain, as you already know

如果代码是:

fprintf(stdout, "%l: flip\n", ms); 
// <-- will also cause the compiler to complain about a invalid format specifier

如果相反,代码将使用与变量“ms”(long int)的“类型”匹配的有效格式说明符

fprintf(stdout, "%ld: flip\n", ms); 
// <-- now compiler happy

格式说明符“%ld”表示“长整数”

fprintf()(或printf())的手册页告诉您所有可用的有效格式说明符及其作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 2013-11-13
    相关资源
    最近更新 更多