【问题标题】:using fflush on C++在 C++ 上使用 fflush
【发布时间】:2011-11-14 21:17:48
【问题描述】:

有人可以帮我在 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;
}

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

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

【问题讨论】:

  • [那不会编译(hasil 没有在任何地方声明)。它也不是 C(C 没有命名空间,也没有 iostream 标头)。]
  • 我通常使用cincout 那么可以不使用printfscanf 吗?是的,可以使用cincout(像往常一样)而不是printfscanf
  • 你是问使用cin和cout的时候怎么刷吗?
  • 是的。我正在做一些研究,fflush(stdout) 与 cout
  • @zeulb 你已经得到了两个很好的 C++ 代码示例,虽然 &lt;&lt; flush 隐藏在 &lt;&lt; endl 中,它实际上只是 &lt;&lt; '\n' &lt;&lt; flush

标签: c++ input interactive fflush


【解决方案1】:

对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;
}

请注意,我故意添加了一些错误检查。

【讨论】:

    【解决方案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' &lt;&lt; std::flush,因此都将行结束并在流上调用 .flush()(这是您的 fflush 等效项)。

    实际上,要获得与您的scanf 通话的真正等价物(而不是在 a 和 b 之间按 Enter),您必须执行以下操作:

    #include <sstream>
    ...
    std::string line;
    std::cin >> line;
    std::istringstream str(line);
    str >> a >> b;
    

    【讨论】:

      【解决方案3】:

      如果您需要 C IO 设施,请包括 &lt;cstdio&gt;。您现在有了std::printfstd::fflush 等。如果您想交织使用C IO 和iostreams,您可以考虑调用std::ios::sync_with_stdio()

      【讨论】:

        猜你喜欢
        • 2011-08-03
        • 1970-01-01
        • 2021-07-22
        • 2019-02-20
        • 2012-07-21
        • 1970-01-01
        • 2018-06-15
        • 2021-12-19
        • 1970-01-01
        相关资源
        最近更新 更多