在Eclipse IDE中执行时交错输入和输出

Interleaving input and output when executing in the Eclipse IDE

本文关键字:输入 输出 Eclipse IDE 执行      更新时间:2023-10-16

您知道eclipse控制台为什么先执行gets函数,然后执行cout吗?我有这个代码:

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
  char str[80];
  cout << "Enter any string: ";
  gets(str);
  cout << "Here is your string: ";
  cout << str;
  return 0;
}
It's just a test
Enter any string: Here is your string: It's just a test

附言:如果我使用DOS控制台,这个程序可以正常工作。

使用cout后添加endl。如果将添加新行并刷新流。

  cout << "Enter any string: " << endl ;
  cout << "Here is your string: " << endl ;

不要使用get!

Eclipse IDE当然不是在执行gets(永远不要使用该函数,它不能安全使用,甚至C标准也禁止它),而是在执行编译器、链接器和后来的编译程序。

问题是Eclipse IDE重定向了标准句柄,从而使标准库错误地将这些流识别为"不是交互式设备",这意味着启用了完全缓冲,并禁用了输入时输出的自动刷新。

解决方案与C流相同:

显式刷新输出。

cout.flush(); // Just flush
cout << endl; // Output newline and flush

"你知道eclipse控制台为什么先执行gets函数,然后执行cout吗?"

原因是在调用operator<<()时,输出缓冲区不会立即刷新。正如另一个答案中所提到的,std::endl这样做了,但也添加了一个额外的换行符,您可能不想在那里使用它。干净的解决方案是显式调用std::ostream::flush()

  cout << "Enter any string: ";
  cout.flush(); // <<<<
  cin >> str;
  cout << "Here is your string: " << str << std::endl;