'printf' vs. 'cout' in C++

后端 未结 16 1737
梦如初夏
梦如初夏 2020-11-22 07:04

What is the difference between printf() and cout in C++?

16条回答
  •  遥遥无期
    2020-11-22 07:35

    I'd like to point out that if you want to play with threads in C++, if you use cout you can get some interesting results.

    Consider this code:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    void task(int taskNum, string msg) {
        for (int i = 0; i < 5; ++i) {
            cout << "#" << taskNum << ": " << msg << endl;
        }
    }
    
    int main() {
        thread t1(task, 1, "AAA");
        thread t2(task, 2, "BBB");
        t1.join();
        t2.join();
        return 0;
    }
    
    // g++ ./thread.cpp -o thread.out -ansi -pedantic -pthread -std=c++0x
    

    Now, the output comes all shuffled. It can yield different results too, try executing several times:

    ##12::  ABABAB
    
    ##12::  ABABAB
    
    ##12::  ABABAB
    
    ##12::  ABABAB
    
    ##12::  ABABAB
    

    You can use printf to get it right, or you can use mutex.

    #1: AAA
    #2: BBB
    #1: AAA
    #2: BBB
    #1: AAA
    #2: BBB
    #1: AAA
    #2: BBB
    #1: AAA
    #2: BBB
    

    Have fun!

提交回复
热议问题