简体   繁体   English

std :: cout和printf数组

[英]std::cout and printf array

    int arrSize = 10;
    double* arr = new double [arrSize];
    for(int i = 0; i < arrSize; i++){
        arr[i] = i;
    }
    for(int i = 0; i < arrSize; i++){       
        printf("%d", arr[i]);
        //std::cout<<arr[i];
    }

Here 这里

  • printf() prints 0000000000. printf()打印0000000000。
  • cout prints 0123456789. cout打印0123456789。

Why ? 为什么呢

Using a wrong format specifier for any particular argument in printf() invokes undefined behaviour . printf()任何特定参数使用错误的格式说明符都会调用未定义的行为

arr is a double array, hence arr[i] produces a double type value. arr是一个double arr数组,因此arr[i]会产生一个double arr[i]类型值。 you need %f format specifier to print that. 您需要%f格式说明符才能打印出来。 If you use %d to print a double , your program faces UB and the result cannot be justified, in can be anything . 如果您使用%d打印double ,你的程序面临UB,结果是没有道理的,在可以是任何东西

OTOH, the << used with cout is an overloaded operator which can adapt based on the type of the supplied variable. OTOH,所述<<使用cout是能够适应基于所提供的变量的类型的重载操作。 So, it prints the output as expected. 因此,它将按预期打印输出。

arr[i] is a double , but %d is the format specifier for int . arr[i]double ,但是%dint的格式说明符。 It is undefined behavior to use the wrong format specifier. 使用错误的格式说明符是未定义的行为。 From the C11 standard, 7.21.6.1/9: 根据C11标准7.21.6.1/9:

If a conversion specification is invalid, the behavior is undefined. 如果转换规范无效,则行为未定义。 If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. 如果任何参数都不是相应转换规范的正确类型,则行为未定义。

There are lots of format specifiers for double that will format the output in different ways, see this reference for a full list. 有很多用于double的格式说明符,它们将以不同的方式格式化输出,有关完整列表,请参见此参考

On the other hand, operator<< for cout has an overload that takes a double directly (#5 in the linked reference), so that just works. 另一方面, cout operator<<具有一个重载,该重载将直接double (链接引用中的#5),因此可以正常工作。

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

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