2012-11-22 33 views
5

通過「C++編程語言」進行閱讀,我目前的任務是編寫一個程序,其中包含兩個變量並確定最小,最大,總和,差異,乘積和比率的價值。如何在執行方程時使用C++開始換行

問題是我無法開始換行。 「\ n」不起作用,因爲我在報價後有變量。和「< < endl < <」只適用於第一行。我把這個問題搞糊塗了,我會盡快完成。

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <cmath> 
using namespace std; 
inline void keep_window_open() {char ch;cin>>ch;} 
int main() 
{ 
    int a; 
    int b; 
    cout<<"Enter value one\n"; 
    cin>>a; 
    cout<<"Enter value two\n"; 
    cin>>b; 
    (a>b); cout<< a << " Is greater than " << b; 
    (a<b); cout<< a << " Is less than " << b; 

    keep_window_open(); 
    return 0; 
} 
+0

注意''\ n「'和'std :: endl'之間的區別在於後者包含'flush';在這種情況下,這對你來說沒有任何意義。 – Keith

+0

你可以像你已經做的那樣連鎖'<<':if(a> b)cout << a <<「大於」<< b <<「\ n」;'。請注意'(a> b);'本身沒有影響;它只是計算'a'是否大於'b'並且對結果不做任何事情。你希望'if(condition){...}'用於條件分支。 –

回答

2

可以輸出std::endl到流移到下一行,像這樣:

cout<< a << " Is greater than " << b << endl; 
5

您正在尋找std::endl,但你希望你的代碼將無法正常工作。

(a>b); cout<< a << " Is greater than " << b; 
(a<b); cout<< a << " Is less than " << b; 

這是不是一個條件,你需要重寫它的

if(a>b) cout<< a << " Is greater than " << b << endl; 
if(a<b) cout<< a << " Is less than " << b << endl; 

方面您也可以發送字符\n創建一個新的行,我用endl,因爲我以爲這就是你正在尋找。有關可能是endl的問題,請參閱this thread

替代寫成

if(a>b) cout<< a << " Is greater than " << b << "\n"; 
if(a<b) cout<< a << " Is less than " << b << "\n"; 

有一些「特殊字符」這樣,\n是新的生產線,\r是回車,\t是標籤,等等有用的東西知道你開始了。

+0

謝謝。正是我在找的東西。 –

+1

在這個程序中,他沒有理由比''n \ n''更喜歡'std :: endl',並且他有理由通常選擇'「\ n」'。 Google「endl慘敗」。 –

+0

@Robᵩ,你意識到這可能是他的第一個C++程序,他只是想要一個新的線? 'endl'可能是它在書中解釋過的......多年沒有讀過它 – emartel