在Eclipse IDE中执行时交错输入和输出
Interleaving input and output when executing in the Eclipse IDE
您知道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;
相关文章:
- 字符的输入/输出操作
- C++ 中文件输入输出中的长长 v/s int
- 要求用户输入C++输出文件名
- 在C++中重载输入/输出运算符
- 从用户获取输入/输出
- 如何选择waveIn/waveOut函数C++使用的输入/输出设备
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 从 2 位输入输出 4 位数字年份
- 标准输入输出操作如何C++完成
- Windows 中应用程序的每秒输入/输出操作数
- 如何初始化可以设置为默认数组并将输入/输出作为数组的类函数?
- 输入/输出和类
- 使用 Octave GNU 访问输入/输出文件
- (C++)分解这个简单的输入/输出代码:
- TensorFlow模型:如何从原始爱好文件中识别输入/输出节点名称
- 干净取消在输入/输出调用中被阻止的 std::线程
- 将线程之间的标准输入/输出重定向
- 输入/输出异或字符串的 C++ 问题
- C++输入/输出错误
- C++输入输出