Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
}
like image 825
Timothy Rebidue Avatar asked Nov 22 '12 04:11

Timothy Rebidue


People also ask

How do I add a new line in C?

The escape sequence \n means newline. When a newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next line on the screen.

How do you add a new line after a variable in C++?

As a programmer, you can use endl or \n to create new line commands in C++.

How do you know if a character is a newline?

Simply comparing to '\n' should solve your problem; depending on what you consider to be a newline character, you might also want to check for '\r' (carriage return).

What does the \n mean in C++?

The symbol \n is a special formatting character. It tells cout to print a newline character to the screen; it is pronounced “slash-n” or “new line.”


2 Answers

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.

like image 169
emartel Avatar answered Oct 14 '22 23:10

emartel


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

cout<< a << " Is greater than " << b << endl;
like image 35
Sergey Kalinichenko Avatar answered Oct 14 '22 23:10

Sergey Kalinichenko