Weird output after inserting std::ends - c++

If I write cout << "Hi!" << ends << "1234";, the 1 will disappear after a while. From C++ reference, I know that std::ends inserts a null character into the stream. But when does this insertion happen?
The full code is
#include <iostream>
int main(int argc, char** argv) {
std::cout << "Hi!" << std::ends << "1234";
return EXIT_SUCCESS;
}
Running the program shows Before
,after maybe 0.5 second, it becomes After.

As far as the language itself is concerned, all cout << ends does is write \0 to the stream. It does not close the stream or cause things to be unexpectedly re-ordered. For the avoidance of any doubt, in your case, the language guarantees that "Hi!" will be be buffered before \0 and that is buffered before "1234".
My understanding is that a terminal ought to silently ignore \0. (It should regard it as an NOP, i.e. no-operation, instruction), but some terminals interpret it, in error, as a space.
That appears to be happening in your case.

Related

Why / when is cout buffer automatically flushed?

I understand from here that if i were to output characters without flushing the buffer ( with endl or cin ) they wouldn't appear on my console until the program ends.
So i tried to make an infinite loop:
for(;;)
{
std::cout << "a" << std::endl;
}
and the same without flushing the buffer:
for(;;)
{
std::cout << "a";
}
They both output forever a, the only difference i can observe is that the latter version of code has some delay time before it starts outputting the letter. The first one starts immediately.
I was expecting the second one to output the chars only if there was a break in the loop, and the program would be terminated.
You are correct that std::endl, or the use of std::cin, causes a flush to occur, and the contents to be immediately output. std::endl is the equivalent of std::cout.put('\n'); std::cout.flush();, where as std::cin and std::cerr are tie()d to std::cout and therefore any operation to either of those executes std::cout.flush() for you.
However, in the second case, std::cout still has an underlying output sequence (an std::streambuf), which is a specified size. Once this buffer is full, the stream is flushed automatically, and you get the output to the console. Filling up this buffer is what you are seeing with the delay time you mentioned.

what is the diffrence between std::cout<< x ; and std::cout<<x<<std::endl;?

I'm a newbie to programming, I started teaching myself yesterday, I've been getting everything but I honestly, do not understand the difference between
std::cout << x;
and
std::cout << x << std::endl;
Nobody has explained this to me, and I'm asking to stay on the safe side.
endl writes a new-line to the stream, so subsequent output will appear on the next line. It also flushes the stream's buffer, usually causing a slow-down.
This flushing means that 99% of the time, endl is a mistake, and you should just write "\n" (or '\n') instead. When you really do want to flush the stream, I think it's better to make that explicit by invoking std::flush instead:
std::cout << x << '\n' << std::flush;
As far as run-time actions goes, this is equivalent to using std::endl, but in terms of making your intent clear, it's drastically superior.
The std::endl adds a newline code to a stream and also flushes the output buffer and std::cout << x is just printing x.
So if you got a code
cout << 5;
cout << 5;
it will be
55
as an output, but if you add a endl to a first cout the output will be
5
5
What i really recommend you is to use '\n' it is much more better than endl.

unexpected behavior when read a character from istringstream

I have a question on the stream behavior, see the following example. What I was expecting is the ss_char and ss_int will be eof state, but just the ss_int will be eof state.
My question is, why isn't ss_char eof state?
Can't I use the operator>>, only the istringstream::get() function, but then why read the value successfully?
Output:
char value: a
int value: 42
ss_char eof: false // why false?
ss_int eof: true
Sorry for my poor English. I’m working on improving my English.
#include <iostream>
#include <sstream>
int main(int /*argc*/, char const * /*argv*/[])
{
char c;
int num;
std::istringstream ss_int("42");
std::istringstream ss_char("a");
if (ss_char >> c)
{
std::cout << "char value: " << c << std::endl;
}
else
{
std::cout << "cannot read char" << std::endl;
}
if (ss_int >> num)
{
std::cout << "int value: " << num << std::endl;
}
else
{
std::cout << "cannot read int" << std::endl;
}
std::cout << std::endl;
std::cout << "ss_char eof: " << std::boolalpha << ss_char.eof() << std::endl; // why false
std::cout << "ss_int eof: " << std::boolalpha << ss_int.eof() << std::endl;
return 0;
}
CppReference says: "This function only reports the stream state as set by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a get(), which returned the last byte of a file, eof() returns false. The next get() fails to read anything and sets the eofbit. Only then eof() returns true."
oefbit will turn true when a read operation attempts to read beyond end of file, but not when it reads exactly to the end of file without trying to go further. When you read the char, it knows it should read a single byte, so this read operation is ok, the read position advance 1 byte, goes to the end, but let say the the stream still haven't noticed that it is indeed the end, it will if you try to read something else. When you read an integer, it tries to read beyond 42 because the length of the integer is not clear, it could have been 42901, so it has to read until it sees an space, and end of line, or eventually the end of the file/stream if there's nothing else to read.
And the result of the operator >> is the stream itself. When it is converted to void* (or bool, depends on c++11 or previous) it works as !fail(), so it tells you if the read or write operation was ok, regardless of whether it reached the end of file (next read operation will fail if it is now at the end).
The EOF condition doesn't actually occur until you try to read past the end of the stream.
In the char case you read exactly one character, the only one available. You don't try to read past the end because there is no need to.
Extracting an int on the other hand attempts to consume as many digits as possible. It reads the 4 and the 2, and then it tries to read again to see if there is another digit to consume, it does attempt to read past the end in this case. It notices that the input came to an end and so finishes the conversion of 42.
when extracting chars, it will pull a single character at a time and skip white spaces on consecutive calls.
when extracting int, the parser attempts to pull as many characters out to form the number. this causes the integer extraction to hit the eof in your test case.

How to use getopt_pp in c++?

I know this is a noob question. I used this example code from here. How is it supposed to work? I thought you can input something for who but it just closes immediately.
#include <iostream>
#include "getopt_pp_standalone.h"
using namespace GetOpt;
using namespace std;
int main(int argc, char* argv[])
{
string who;
GetOpt_pp ops(argc, argv);
ops >> Option('n', "name", who, "world" ); /* the default name is 'world' */
cout << "Hello " << who << "!" << endl;
return 0;
}
Variants of getopt get options from the command line rather than input by a user.
You will need to run your program with something like:
myprog -n Pax
If you want interactive input from the user, get rid of the getopt stuff altogether and just use the streams, such as:
std::cout << "Identify yourself, interloper!\n";
std::cin >> who;
std::cout << "Hello, " << who << ", my name is Pax.\n";
A few other things to impart:
First, you may need to put a getchar() (or cin >> who) before the return if you're running in an IDE that closes the execution window instead of waiting. Otherwise, the output will go to the window and immediately disappear.
Second, while it's probably okay for small programs, using namespace std can cause problems with more substantial projects (in terms of polluting the standard namespace, see here for a good explanation). I prefer to fully qualify my calls, such as:
std::cout << "blah, blah, blah\n";
Third, endl is used far too often by most developers. Most times you should just either use '\n' instead, or just tack on \n to the end of a string like "Hello, world!\n". That's because the \n way doesn't force possibly inefficient flushing of the stream like endl does. That's covered here.

Why does endl get used as a synonym for "\n" even though it incurs significant performance penalties?

This program:
#include <iostream>
#include <cstdlib>
#include <string>
int main(int argc, const char *argv[])
{
using ::std::cerr;
using ::std::cout;
using ::std::endl;
if (argc < 2 || argc > 3) {
cerr << "Usage: " << argv[0] << " [<count>] <message>\n";
return 1;
}
unsigned long count = 10000;
if (argc > 2) {
char *endptr = 0;
count = ::std::strtoul(argv[1], &endptr, 10);
if ((argv[1][0] == '\0') || (*endptr != '\0')) {
cerr << "Usage: " << argv[0] << " [<count>] <message>\n";
return 1;
}
}
const ::std::string msg((argc < 3) ? argv[1] : argv[2]);
for (unsigned long i = 0; i < count; ++i) {
cout << i << ": " << msg << '\n';
}
return 0;
}
when timed like so:
$ time ./joe 10000000 fred >/dev/null
real 0m15.410s
user 0m10.551s
sys 0m0.166s
takes 15.4 seconds of real time to execute. Replace the output line with this: cout << i << ": " << msg << endl; and you end up with something like this:
$ time ./joe 10000000 fred >/dev/null
real 0m39.115s
user 0m16.482s
sys 0m15.803s
As you can see, the time to run more than doubles, and the program goes from spending minimal time in the OS to spending nearly half of it's time in the OS.
Both versions of the program have identical output, and are guaranteed by the standard to have identical output on every platform.
Given this, why do people persist in using endl as a synonym for '\n'?
Edit: In case it isn't obvious, this question is intended to be a leading question and is here for instructional purposes. I know why the performance penalty exists.
I'm not certain. Inserting std::endl into the output stream is defined as being equivalent to inserting .widen('\n') and then calling flush() and yet many programmers persist in using std::endl even when there is no cause to flush, for example they go on to immediately output something else.
My assumption is that it comes from an incorrect belief that it is somehow a more portable because it doesn't explicitly use a specific newline character. This is incorrect as \n must always be mapped to the system's correct newline sequence for non-binary files by the stream library.
Afaik, endl also flushes the stream, which may be the cause of the performance penalty.
Not everyone cares so much about performance. For some applications, guaranteeing the stream is flushed is much more important.
Edit: Also, I find endl easier to type than '\n' :-)
I tend to use endl with on stringstreams as it makes it easy to spot missing linebreaks.
My guess is that instructional texts use std::endl with the belief that it's simpler and less confusing for beginners, and afterward people got accustomed to using it.
The real question is, why did the compiler make such a dogs breakfast of compiling the endl version? If they're guaranteed to have the same semantics, then they should also have the same runtime.
Edit: obviously, I wasn't aware that endl flushed the stream... that's what you get for not looking it up.