You see, this program is supposed to output whatever character you type and stops when you input a full stop '.'
The problem here is, that when I input a long set of characters (for example, 'Hello'), the program outputs the word 'Hello' again for me. Aren't char type variables supposed to only store one character? Aren't I supposed to get only the letter 'H' when I type in 'Hello'??
Could you please tell me what's wrong with the program and what can I do to correct it?
It's not the fault of the program, but rather of cin. You see, cin doesn't clear the buffer after you input a variable- it simply takes from the beginning and deals with it that way. In other words, it grabs the 'H' from Hello, puts it into ch, displays it, then hits the cin call again- except "ello" is still in the cin buffer. This line:
Try typing H.ello, or He.llo and you should be able to see what is happening.
It will continue to read characters until it reads a '.', then it will break out of the loop.
<edit>
Also, it will never leave the loop until it reads a '.'. In other words even after it prints Hello, it is still waiting in the loop for a '.' to be entered.
It's not the fault of the program, but rather of cin. You see, cin doesn't clear the buffer after you input a variable- it simply takes from the beginning and deals with it that way. In other words, it grabs the 'H' from Hello, puts it into ch, displays it, then hits the cin call again- except "ello" is still in the cin buffer. This line:
should clear out the buffer if you stick it right after line 16, but before line 17.
@Ispil thanks! it worked like magic after I added that line!
but could you please explain to me what exactly does this line do? I understand that it's cin.ignore but what does it exactly ignore?
The first value is the number of input letters for it to ignore- the weird "numeric_limits" thing is just a way to tell it to ignore up to whatever the max number of characters that can be stored in the cin buffer on that specif computer. The second parameter is an "up-to" bit- once it hits a newline character, it stops ignoring. Since you finish input by hitting enter, therefore you must end your input on a newline- hence why that works. You could replace the numeric_limits bit with, say, 10000, and it'll still work.