Timothy Rebidue
Timothy Rebidue

Reputation: 101

How to start a newline in C++ while doing equations

Im reading through "The C++ Programming Language" and my current assignment is to make a program that takes two variables and determines the smallest, largest, sum, difference, product, and ratio of the values.

Problem is i can't start a newline. "\n" doesn't work because i have variables after the quote. And "<< endl <<" only works for the first line. I googled the hell out of this problem and im coming up short.

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

Upvotes: 8

Views: 52706

Answers (2)

emartel
emartel

Reputation: 7773

You are looking for std::endl, but your code won't work as you expect.

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

This is not a condition, you need to rewrite it in terms of

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

You can also send the character \n to create a new line, I used endl as I thought that's what you were looking for. See this thread on what could be issues with endl.

The alternative is written as

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

There are a few "special characters" like that, \n being new line, \r being carriage return, \t being tab, etc... useful stuff to know if you're starting.

Upvotes: 8

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You can output std::endl to the stream to move to the next line, like this:

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

Upvotes: 3

Related Questions