cout 和 cerr 的控制台输出顺序错误

Wrong console output order of cout and cerr

我想在简介中没有任何内容写入时输出错误,并且用户可以在错误输出后再次编写简介。 问题是控制台输出的顺序错误。 为什么会这样,我该如何解决?

#include <iostream>
#include <string>

using namespace std;

int main() {
    string introduction;
    cout <<"Introduction:" << endl;
    getline(cin,introduction);


     if(introduction.size()==1)
     {
         cerr << "ERROR PLEASE WRITE AN INTRODUCTION!" << endl;
         cerr.flush();
         cout <<"Introduction:" << endl;
         getline(cin,introduction);
     }
    return 0;
}

控制台输出:

    Introduction:

    Introduction:
    ERROR PLEASE WRITE AN INTRODUCTION!

新编辑:将 main 编辑到源代码中

我的解决方案:

#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
unsigned int microseconds;
int main() 
{
    string introduction;
    cout <<"Introduction:" << endl;
    getline(cin,introduction);
    cout << introduction.size()<< endl;

    if(introduction.size()==1)
    {
         cerr << "ERROR PLEASE WRITE AN INTRODUCTION!" << endl;
         microseconds=1000;
         usleep(microseconds);
         cout <<"Introduction:" << endl;
         getline(cin,introduction);
    }
    return 0;
}

完美解决方案:

#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
unsigned int microseconds;

int main() 
{
    string introduction;
    cout <<"Introduction:" << endl;
    getline(cin,introduction);


    while (introduction.size() == 1) 
    {

        cerr << "ERROR PLEASE WRITE AN INTRODUCTION!" << endl;
        microseconds = 1000;
        usleep(microseconds);
        cerr.flush();
        cout << "Introduction:" << endl;
        getline(cin, introduction);

    }
    return 0;
}