0

有人可以帮我fflush在 C++ 中使用吗

这是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;
}

这是获取交互式输入的程序。

我通常使用cincout所以可以不使用printfandscanf吗?

4

3 回答 3

3

转换为 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-11T19:43:34.207 回答
2

虽然我还没有完全理解你的问题,但你的程序的 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-11T19:39:21.290 回答
1

如果您需要 C IO 设施,请包括<cstdio>. 你现在有std::printf等等。如果你想交织使用 C IO 和 iostreams,std::fflush你可以考虑调用。std::ios::sync_with_stdio()

于 2011-09-11T19:30:42.423 回答