The right thing to do when you want to print a character, of course, is to print that character:
char ch;
if(std::cin >>ch)
std::cout << ch;
else
// handle input error
And if you, for whatever reason, want a newline behind every character, then do just that:
std::cout << char << '\n';
Note: You will also see std::endl
used for outputting a newline, but std::endl
does two things: it outputs a '\n'
and flushes the output buffer. While the latter isn't a problem when outputting to the console (it's still faster than a human will be able to read it), I have seen applications becoming to slow (on file output) due to the use of std::endl
instead of '\n'
. So you'd better learn from the beginning to pay attention whether you need those buffers flushed or not.
Note that, where you're doing
pChar++;
*pChar = '\0';
you're invoking the dreaded Undefined Behavior: With pChar++
you are incrementing the pointer to point behind your variable (which is fine), and with *pChar = ...
you are writing to whatever memory happens to be behind your variable.
In practice, this will likely corrupt your stack, hopefully making your application crash in the very next moment. In theory, however, this invokes undefined behavior, which, according to the C++ standard, might do anything (including the often cited possibility that it might format your disk).
Do not write to memory that you don't own.
It is hard for beginners to get pointers right, so just avoid them wherever you can. You can do a lot with C++ without ever manually fiddling with pointers.