2013-10-29 34 views
0

我想輸入我的函數的值,它是這樣的:運行函數的std :: istream的

int funkcija(std::istream & in) { 
    int value(0); 
    in >> value; 
    if(not in) throw std::exception(); 
    if(value%2 == 0) { 
     return (value/2); 
    } 
    else return (value*3)+1; 
} 

當我嘗試運行它:

int i(0); 
std::cout << "Input a number: "; 
std::cin >> i; 
funkcija(i); 

我得到一個錯誤: .. \ working.cpp:17:14:錯誤:類型'std :: istream & {aka std :: basic_istream &}'的引用無效初始化''int' .. \ working。 cpp:7:5:錯誤:在傳遞'int funkcija(st d :: istream &)'

這是什麼意思,以及如何解決它?謝謝!

+0

不應該呼叫是'I = funkcija(CIN);'??? –

回答

3

您正在試圖通過您已經閱讀整,請嘗試:

std::cout << "Input a number: "; 
int i = funkcija(std::cin); 
std::cout << i << " "; 

雖然這工作,它似乎很奇怪。考慮將輸入和輸出處理與計算分離以改進您的設計。改變功能到:

int funkcija(int value) { 
    if(value%2 == 0) { 
     return (value/2); 
    } 
    else return (value*3)+1; 
} 

,也許調用它是這樣的:

std::cout << "Input a number: "; 
int i; 
if(!(std::cin >> i)) throw std::exception(); 
do { 
    i = funkcija(i); 
    std::cout << i << " "; 
} while(i != 1); 
+0

謝謝你的回答。我試過了,它可以工作,但我必須連續多次運行該函數,直到結果爲1.所以我在考慮一個do-while循環。任何其他想法? – AlesSvetina

+0

@AlesSvetina更新了答案。 –

+0

這是有效的。我正在從其中一本書中學習,這是這項任務。在這本書中,他們使用std :: istream並且說要升級程序,以便它能運行函數,直到結果爲1.所以我只是假設我必須用istream來完成。無論如何謝謝你的答案! – AlesSvetina

0

我的類型是int not istreeam - 你傳遞給我的函數,因此它抱怨說它是一個int而不是一個istream。你可以直接將std :: cin傳遞給函數。

相關問題