This code is written in C++ and for reasons that I don't quite understand it is written twice. I would expect that after inputting a random char it would display the char once and the String lower to it once as well. But I don't get this as output. What am I missing?
Solution: Adding a cin.ignore() statement disregards the return that is read in as well. Making my code go through the loop once.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char letter;
letter = cin.get();
while (letter!= 'X')
{
cout << letter << endl;
cout << "this will be written twice for ununderstandable reasons";
letter = cin.get();
}
}
Example:
If I were to write in cmd scrn c
, I'd get a c
back + twice the phrase this will be written twice for ununderstandable reasons
. So what I thought to be the output
c
this will be written twice for ununderstandable reasons
is actually
c
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
The text 'this will be written twice..' will not necessarily print twice.
Type 'qwerty' + ENTER and your stream will have "qwerty\n" within and you'll see this output:
Exactly that many as string "qwerty\n" has characters. The problem is that
Puts all chars that you type into a stream/buffer (not your letter char) but handles one char every cin.get() invocation.
When you type 'abcXd' + enter - the program will print above line 3 times and stop on X.
as everyone already mentioned,
cin
will append the newline marker\n
every time you hit enter. another solution is to placecin.ignore();
after everycin.get();
.You forgot about the newline. cin reads every character, which includes the newline you type after typing your character. If you don't want this behaviour, you have to specifically check for newline.
It happens because cin.get() reads
new-line
character too. Try to pressEnter
without any symbols or type some string, likeabc
. You need to handle it, e.g.:You are reading every character with the unformatted
get()
function, including the newline character each time you hit return.Depending on what you're trying to do, you could use formatted input (
cin >> c
) to skip all whitespace; or you could test each character and ignore things like newline that don't interest you; or you could usegetline(cin, some_string)
to read a whole line, and then process that.When you type in a character the new-line character (from pressing enter) is also in your input buffer.
From the C-Reference:
Just use a
cin.sync()
after everycin.get()
to clear the buffer and you should be good to go.