can I Remove "endl" in ( cout<<" "<<endl ) in C++? - c++

I am beginner at C++, my question is can I remove endl the one at the end of cout like :
cout<<" "<<endl;
I don't want return to new line . If I can't remove it, what should I do?

Elephant in the room: remove the endl from the cout.
But in case you don't own that code, you could try "\033[F", which, if your terminal supports it, moves you to the previous line.
Another possibility would be to redirect the cout buffer using rdbuf to an ostream that you control. You could (i) redirect, (ii) call the function that writes the errant cout with the new line and (iii) inspect your ostream and write to the original buffer, this time omitting the endl. Switch everything back once you're done.

Yes of course you do not need to use std::endl every time you use <<. As an example a simple way to print a vector with spaces between the elements would look like:
std::vector<int> foo = {1,2,3,4,5};
for (auto e : foo)
std::cout << e << " ";
Here we never use a endl. You cout also just use \n at the end of a string literal and that will put a newline in the buffer as well.
std::cout << "test\n";
std::cout << "this will be on a new line";
Notice that I don't put a newline in the last cout<< so if there is anymore output it will start off right after the "e" in "line".

Yes you can remove endl. It is an optional parameter to the << stream operator of which there are many. If you don't include it then a new Carriage Return/Line Feed character will not be output and therefore text will appear on the same line in the output (presumably console).
For example
cout << "Hello, World" << endl;
would become:
cout << "Hello, World";
or to make the point another way you could write:
cout << "Hello,";
cout << " World";
There are lots of other examples out there too, here's one for starters: http://www.cplusplus.com/doc/tutorial/basic_io/

cout<<"Your message here.";
It's as simple as that. Were you trying to do something like...
cout<<"Your message here."<<; ....? This is wrong as:
The << operator signifies that something comes after the "" part. You don't have any in this case.

Related

Removing end of a line after calling a void function

I have a void function that recursively prints an AVL tree in order, using a comma and a space between every key.
After the void function is called, I want to remove the last comma and space, but I am not sure how. I tried doing std::cout << '\b' << '\b', but it doesn't do anything.
What I'm trying is something like:
void printInoder(root){
InorderHelper(root);
cout << '\b' << '\b' << endl;
}
The name backspace is a bit misleading. It doesn't print a space.
If the output ends with , you probably want std::cout << "\b\b \b\n";. That is, step two steps back, print a space over the , and then step one step back. Since you do a newline last, the last \b can be omitted.
std::cout << "\b\b \n";
It would probably be better to fix it at the source and not print the characters you want to erase at all.

C++ won't print trailing whitespace

In my simple program to learn C++, I am asking the user their name and then greeting them.
#include <iostream>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
}
However, here is my result in CLion:
I expected the program to print out a trailing whitespace after the prompt for my name. However, it prints the space after I give the program input. I have only experienced this in CLion, but not in other IDEs. Why is this happening, and how can I fix this?
You need to flush your stream:
std::cout << "Enter your name: " << std::flush;
std::cout is a buffered stream which means that while your write to it isn't immediately written to the underlying device, but it is stored in a buffer. This is done for performance reasons. std::endl has an implicit flush operation, that's why you don't notice this if you always add a std::endl before you request input. Otherwise, like you've seen that can happen.

What is the sequence a compiler processes information (strings, manipulators etc.) when encountered with an extraction or insertion operator?

I am unsure as to why this line works. How does a compiler work to make this line of code perfectly legal. Does the cout process information from left to right, neglecting the information till the next extraction operator?
How does a compiler identify how to sequence the multiple existing strings?
std:: cout << "Hello world" << " this is a new line" << endl;
This works based on two mechanics:
When cout (or cin or another stream from the <iostream> library) has the << or >> operator called, it returns itself after doing the input or output. Therefore, cout << "Hello world" works just like cout for the rest of the line.
The operator<< call is left-to-right associative; that is, your line is equivalent to ((std::cout << "Hello world") << " this is a new line") << endl;. Combined with point 1, this means that it works like running cout << "Hello world";, followed by cout << " this is a new line"; and cout << endl;.
As a side note, in most cases you don't actually need endl. You should just include a newline in the string itself, as " this is a new line\n". The only time you need to use endl is if you actually need the line to appear on the screen right away, which you usually don't. Because endl forces the line to appear immediately (it flushes the buffer), it takes a lot longer than just using a newline character.
<< is really just operator<<. That overload for std::ostream returns itself to allow chaining of multiple operator<< calls so really it's just:
foo.print("Hello world").print(" this is a new line").print("\n");

Is cout.put() recommended over cout<< for printing characters

Background
IIRC, from Release 2.0 C++ stores single-character constants as type char and NOT int. But before Release 2.0 a statement like
cout<<'A'
was problematic as it displays the ASCII value of 'A' ie 65 whereas:
char ch='A';
cout<<ch;
would display the right value ie 'A'.
Since the problem has been rectified in Release 2.0. I believe cout.put() lost the advantage it had over cout<<.
Question
Is there any other reason for recommending cout.put() over cout<< for printing characters?
There are a few differences between cout<< and cout.put, or should we say the overloaded << operator and the put method from std::basic_ostream because this is not really limited to the global instance: cout.
The << operator writes formatted output, the put method does not.
The << operator sets the failbit if the output fails, the put method does not.
Personally I would go with the << operator in almost all cases, unless I had specific needs to bypass the formatted output or not setting the failbit on error.
Using them can result in the following differences of output:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "Character: '" << setw(10) << 'A' << setw(0) << "'" << endl;
cout << "Character: '" << setw(10);
cout.put('A');
cout << setw(0) << "'" << endl;
return 0;
}
Outputs:
Character: ' A'
Character: 'A'
See the above in action: http://ideone.com/9N0VYn
Since the put method is unformatted it does not respect the manipulator set, there might be situations where that is indeed what you intend. But since it sounds like you only want to print out the character, I would prefer the << operator, which respects the formatting.
And then there is the case of the failbit which is not being set, and that might even be more crucial.

How to break out of this for loop: `for (; cin >> A;);`

for (cout << "\nEnter the Sentence now:";
cin >> Ascii;
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)Ascii + RandomNumberSubtract << endl);
Probably the best advice is don't be clever. Not only do you make it hard for anyone else* to read, understand, and modify your code, you run a real risk of outsmarting yourself.
Thus, don't try to do weird and clever things to implement your loop. Just do things naturally. If they don't naturally fit into how for or while or do ... while statements are structured, then just write a generic loop and use break statements to deal with leaving the loop. e.g.
while (true) {
// Some stuff
if (i_should_break_out_of_the_loop) {
break;
}
// Some more stuff
}
This is pretty much always better than doing things like torturing the for statement in the way you have.
Once you have a clear, easily comprehensible loop, it should be relatively easy to modify it to suit your needs. (or to ask a clearer and more focused question)
*: "anyone else" also includes you three weeks from now, after you've had time for it leave your short term memory.
I strongly advise you to turn this loop into a while loop. However the following is true whether or not you do:
Just enter an EOF, then the loop will terminate.
How an EOF is input will depend on your OS (and possibly also on your terminal settings). On Linux (under default terminal settings) you get an EOF pressing Ctrl+D at the beginning of the line. On Windows, I think it's Ctrl+Z. On Mac I have no idea.
Of course you could also redirect stdin for your program to come from a file (in which case EOF is — as you would guess — generated at the end of file), or from a pipe (in which case EOF is generated as soon as the writing program closes the pipe).
If the variable Ascii is not of type char or string, you may also enter something that cannot be parsed as that variable's data type (e.g. if reading an int, anything other than a number will cause the stream to report failure and thus the loop to terminate).
You also might want to add another end condition then in the loop body (which in your for loop is currently just an empty statement). For example, you might decide that a percent sign should terminate your loop; then you could write (I'm still assuming the type of Ascii which you didn't provide is char):
cout << "\nEnter the Sentence now:";
while(cin >> Ascii)
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)Ascii + RandomNumberSubtract << endl);
if (Ascii == '%')
break;
}
However note that normally operator<< skips whitespace; I guess you don't want whitespace skipped. Therefore you probably shouldn't use operator<< but get; this will also allow you to use the end of line as end condition:
cout << "\nEnter the Sentence now:";
while(std::cin.get(Ascii) && Ascii != '\n')
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)Ascii + RandomNumberSubtract << endl);
}
However in that case, it's better to read the line in one step and then iterate through it:
cout << "\nEnter the Sentence now:";
std::string line;
std::getline(std::cin, line);
for (std::string::iterator it = line.begin; it != line.end(); ++it)
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)*it + RandomNumberSubtract << endl;
}
Note that in C++11, you can simplify this into
cout << "\nEnter the Sentence now:";
std::string line;
std::getline(std::cin, line);
for (auto ch: line)
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)ch + RandomNumberSubtract << endl;
}