using fflush on C++

2019-08-22 12:21发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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;