2014-10-08 49 views
-3

我一直在尋找解決方案,但找不到我需要/想要的。C++簡單流操作與ostream和istream?

我想要做的就是將用於std :: cout的流傳遞給一個處理它的函數。什麼到目前爲止我用的是一個模板函數:

template<typename T> 
void printUpdate(T a){ 
    std::cout << "blabla" << a << std::flush; 
} 

int main(int argc, char** argv){ 

    std::stringstream str; 
    str << " hello " << 1 + 4 << " goodbye"; 
    printUpdate<>(str.str()); 

    return 0; 
} 

我寧願是這樣的:

printUpdate << " hello " << 1 + 4 << " goodbye"; 

std::cout << printUpdate << " hello " << 1 + 4 << " goodbye"; 

我試圖做的事:

void printUpdate(std::istream& a){ 
    std::cout << "blabla" << a << std::flush; 
} 

但這給了我:

error: invalid operands of types ‘void(std::istream&) {aka void(std::basic_istream<char>&)}’ and ‘const char [5]’ to binary ‘operator<<’ 
+0

你不能將數據輸出到的輸入流。將參數更改爲'std :: ostream&a'。另外,'flush'沒有爲輸入流定義。 – 2014-10-08 15:25:02

+0

我也試過了。同樣的錯誤: 錯誤:類型'無效(std :: ostream&){aka void(std :: basic_ostream &)}'和'const char [5]'爲二元操作符<<' – 2014-10-08 15:26:41

+0

的操作數無效'main'函數,您需要將流類型提供給'printUpdate'函數調用,例如'printUpdate '。 – 2014-10-08 15:29:50

回答

1

您無法將數據輸出到輸入流,這不是一件好事。 變化:

void printUpdate(std::istream& a){ 
    std::cout << "blabla" << a << std::flush; 
} 

要:

void printUpdate(std::ostream& a){ 
    std::cout << "blabla" << a << std::flush; 
} 

注流類型變化。

編輯1:
此外,你不能輸出流中另一個流,至少std::cout
返回值<< aostream類型。
cout流不喜歡被饋送另一個流。

更改爲:

void printUpdate(std::ostream& a) 
{ 
    static const std::string text = "blabla"; 
    std::cout << text << std::flush; 
    a << text << std::flush; 
} 

編輯2:
你需要一個流傳遞給需要一個流的功能。
您無法將字符串傳遞給需要流的函數。
試試這個:

void printUpdate(std::ostream& out, const std::string& text) 
    { 
    std::cout << text << std::flush; 
    out << text << std::flush; 
    } 

    int main(void) 
    { 
    std::ofstream my_file("test.txt"); 
    printUpdate(my_file, "Apples fall from trees.\n"); 
    return 0; 
    } 

鏈接的輸出流 如果你想鏈的東西到輸出流,就像從功能效果,功能要麼返回打印(流式傳輸的對象)或相同輸出流。

實施例:

std::ostream& Fred(std::ostream& out, const std::string text) 
    { 
    out << "--Fred-- " << text; 
    return out; 
    } 

    int main(void) 
    { 
    std::cout << "Hello " << Fred("World!\n"); 
    return 0; 
    } 
+0

我也試過。相同的錯誤: 錯誤:無效操作數的類型'無效(std :: ostream&){又名無效(std :: basic_ostream &)}'和'const char [5]'二進制'操作符<<' – 2014-10-08 15:29:45

+0

錯誤消息與我編輯中的示例不匹配,因爲「text」是一個「std :: string」,不是由5個字符組成的數組。 – 2014-10-08 15:37:32

+0

對不起,錯誤信息來自函數調用: printUpdate <<「abcd」; – 2014-10-08 15:43:54