2011-09-11 18 views
0

fflush有人可以幫助我使用C中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所以有可能不使用printfscanf

+5

問題是什麼? – littleadv

+0

[這不會編譯('hasil'沒有在任何地方聲明)。它不是C('C'沒有命名空間,也沒有iostream頭文件)。] – Mat

+0

我通常使用'cin'和'cout',所以有可能不使用'printf'和'scanf'?是的,可以使用'cin'和'cout'(照常),而不是'printf'和'scanf'! –

回答

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

請注意,我故意添加了一些錯誤檢查。

1

如果您需要C IO設施,請包括<cstdio>。您現在有std::printfstd::fflush等。如果您想要交織使用C IO和iostream,則可以考慮調用std::ios::sync_with_stdio()

1

雖然我還沒有完全明白你的問題,你的程序的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之間的輸入),你就必須這樣做:

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