using fflush on C++

2019-08-22 12:47发布

Can someone help me using fflush in C++

Here is a sample code in 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;
}

This is program for getting interactive input.

I usually use cin and cout so is it possible not using printf and scanf?

3条回答
疯言疯语
2楼-- · 2019-08-22 13:01

Although I haven't completely understood your question, the C++ version of your program would be something like this (assuming hasil should be 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;
}

Note, that std::endl is equivalent to '\n' << std::flush and therefore both puts the line end and calls .flush() on the stream (which is your fflush equivalent).

Actually to get the real equivalent to your scanf call (and not press enter between a and b), you would have to do something like:

#include <sstream>
...
std::string line;
std::cin >> line;
std::istringstream str(line);
str >> a >> b;
查看更多
我命由我不由天
3楼-- · 2019-08-22 13:19

If you have need for C IO facilities, include <cstdio>. You now have std::printf and std::fflush etc. You might consider calling std::ios::sync_with_stdio() if you want to use C IO and iostreams interwovenly.

查看更多
别忘想泡老子
4楼-- · 2019-08-22 13:22

The translation to C++ programming style is this:

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

Note that I deliberately added some error checking.

查看更多
登录 后发表回答