我想在介绍中没有写入任何内容时输出错误,并且用户可以在错误输出后再次编写介绍。 问题是控制台输出的顺序错误。 为什么会这样,我该如何解决?
#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!
新编辑:编辑主要源代码
我的解决方案:
#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;
}
答案 0 :(得分:-2)
完美的解决方案:
#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;
}