using fflush on C++

南楼画角 提交于 2019-12-12 01:25:10

问题


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;


来源:https://stackoverflow.com/questions/7380600/using-fflush-on-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!