【问题标题】:format specifies type 'int' but the argument has type 'unsigned long'format 指定类型“int”,但参数的类型为“unsigned long”
【发布时间】:2014-01-28 03:38:51
【问题描述】:

我是 obj-c 的新手。 如何解决? format 指定类型“int”,但参数的类型为“unsigned long”

int main(int argc, const char * argv[])
{
    const char *words[4] = {"aardvark","abacus","allude","zygote"};
    int wordCount = 4;
    int i;

    for(i=0;i<wordCount;i++){
        NSLog(@"%s comprises %d chars", words[i], strlen(words[i]));
    }

    return 0;
}

【问题讨论】:

    标签: objective-c c arrays long-integer unsigned


    【解决方案1】:

    你必须使用NSLog中的好格式(好像和printf和cie使用的格式一样):

    NSLog(@"%s comprises %zu chars", words[i], strlen(words[i]));
    

    或者你可以投strlen的返回:

    NSLog(@"%s comprises %d chars", words[i], (int)strlen(words[i]));
    

    【讨论】:

    • @MartinR 对不起,我从一个不完全正确的快速回答开始,然后修复它并重新修复它(感谢 Eric)。是的,最后是一样的,我很抱歉......但是谁在乎呢?
    • 很抱歉反应过度。我已删除我的评论。
    【解决方案2】:

    strlen() 返回一个size_t,可以是32位或64位,取决于使用的 架构。

    打印size_t 的正确格式是%zu

    NSLog(@"%s comprises %zu chars", words[i], strlen(words[i]));
    

    http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html 对于“z”和其他长度修饰符:

    • z
      指定以下 [...] 转换说明符适用于 size_t 或相应的有符号整数类型参数;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-03
      • 2017-09-04
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多