有人能帮我在C++中使用fflush吗?
下面是一个用C编写的示例代码
#include <stdio.h>
using namespace std;
int a,b,i;
char result[20];
int main() {
scanf("%d %d\n", &a, &b);
for (i=1; i<=10; i++) {
printf("5\n");
fflush(stdout);
gets(result);
if (strcmp(result, "congratulation") == 0) break;
}
return 0;
}这是一个用于获取交互式输入的程序。
我通常使用cin和cout,所以有没有可能不使用printf和scanf
发布于 2011-09-12 03:43:34
C++编程风格的转换是这样的:
#include <iostream>
using std::cin;
using std::cout;
using std::string;
int main() {
string line;
int a, b;
if (cin >> a >> b) {
for (int i = 0; i < 10; i++) {
cout << "5" << std::endl; // endl does the flushing
if (std::getline(cin, line)) {
if (line == "congratulations") {
break;
}
}
}
}
return 0;
}请注意,我故意添加了一些错误检查。
发布于 2011-09-12 03:39:21
虽然我还没有完全理解你的问题,但你的程序的C++版本应该是这样的(假设hasil应该是result):
#include <iostream>
int main() {
int a,b,i;
std::string result;
std::cin >> a >> b;
for (i=1; i<=10; i++) {
std::cout << "5" << std::endl;
std::cin >> result;
if (result == "congratulation") break;
}
return 0;
}请注意,std::endl等同于'\n' << std::flush,因此两者都将行尾放在流上并调用.flush() (这是您的fflush等效项)。
实际上,要获得与scanf调用相同的结果(而不是在a和b之间按enter键),您必须执行以下操作:
#include <sstream>
...
std::string line;
std::cin >> line;
std::istringstream str(line);
str >> a >> b;发布于 2011-09-12 03:30:42
如果您需要C IO工具,请包括。你现在有了std::printf和std::fflush等等,如果你想同时使用C和iostreams,你可以考虑调用std::ios::sync_with_stdio()。
https://stackoverflow.com/questions/7380600
复制相似问题