2012-11-22 28 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