For the following code, on my PC, char \0
will always results in a space (when printing using cout
). However, on my friend's PC, the result of char \0
will always results in a char a
. Code and screenshots are as follows:
#include <iostream>
using namespace std;
// Function main
int main()
{
cout << "xxx" << '\0' << "yyy" << endl;
return 0;
}
Left: on my PC. Right: on my friend's PC.
What's going on here? Why are the results different on different PCs?
PS:
The results will still be different even we share the same executable
exe
file (i.e. compiled on my PC and run on both PCs).We both use visual studio 2010 also with same project character set.
There maybe some buffer overrun here, but please pay attention to the fact that I will always get a
space
while my friend will always get a chara
.It shares the same feature if we both do
cout<<ends
.
For a "non-printable character" (which for ASCII is anything outside the range of 0x20-0x7e [*]), output is technically undefined, and the actual visual output will depend on several things:
The actual output device - if you view the character on a Windows command line prompt, it may well look different to a Terminal window under Linux, and using a genuine (30+ year old) VT100 terminal, it will most likely look different again. (In fact, when I first used to write code for terminals that used serial input, we used to "pad" certain control sequences with NUL characters, because the terminal would drop some characters when the escape sequence was "complicated" - say a clear-screen, it may not receive the next 5-6 characters, so we'd add an extra 10 NUL characters to, so that we'd lose the NUL's rather than part of the meaningful text we wanted to print on the screen).
When applicable, the font selected to show the text may also matter (this appears to be the case in this particular situation, but don't rely on it). Of course, this applies also to printable characters, but aside from some "special" fonts (Zapf Dingbats, Symbols are obvious examples), the "printable range" does match what we expect. The "non-printable" range is not so well-defined.
The method of actual printing - for example using
cout
orprintf
will have a different result than "poking characters into the frame-buffer memory on a PC [in text mode]".For consistent results of printing non-printable characters, you will need to process them into something that is defined as printable.
[*] Many systems support extended ranges, for example the original IBM/PC has a range of 0x20-0xff, and modern systems use multiple bytes to represent characters that are "non-printable" in for example UTF-8 encoding, where commonly used characters [in European languages] are encoded with a single byte, and characters that are less common get a two, three or four-byte encoding. Even here, the actual output depends on the exact font chosen.