#cout and printf give a different output, why?

3 messages · Page 1 of 1 (latest)

chrome jolt
#
#include <iostream>
#include <stdio.h>

using namespace std;
 
int main() {
    int num = 250;

    printf("%#1x\n", &num);
    cout << hex << &num << endl;
    
    return 0;
}
0xf1dffa0c
0x56f1dffa0c
foggy ibex
#

printf is a c-style formatting str, whereas cout is a object of the <iostream> class in C++, that's why you're getting different outputs. however, the way printf and cout print the memory address of num is different. printf with %#1x specifier prints the memory address with a leading 0x prefix, whereas cout simply prints the memory address in hexadecimal format without a prefix. This difference in formatting is why the output of printf and cout statements is not the same.

#

try to not use both printf and cout statements in the same program, as they have different output buffering mechanisms, which can interfere with one another in your code. try to stick to one or the other instead