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
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 use getline(cin, some_string)
to read a whole line, and then process that.
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:
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
this will be written twice for ununderstandable reasons
Exactly that many as string "qwerty\n" has characters. The problem is that
cin.get()
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.
It happens because cin.get() reads new-line
character too. Try to press Enter
without any symbols or type some string, like abc
.
You need to handle it, e.g.:
while (letter = cin.get()) {
if (!isalpha(letter)) { continue; }
// handling user inputted alpha
}
When you type in a character the new-line character (from pressing enter) is also in your input buffer.
From the C-Reference:
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).
Just use a cin.sync()
after every cin.get()
to clear the buffer and you should be good to go.
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.
while (letter!= 'X')
{
if (letter == '\n')
{
letter = cin.get();
continue;
}
cout<<letter<<endl;
cout<<"this will be written twice for ununderstandable reasons";
letter= cin.get();
}
as everyone already mentioned, cin
will append the newline marker \n
every time you hit enter. another solution is to place cin.ignore();
after every cin.get();
.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char letter;
letter = cin.get();
cin.ignore();
while (letter!= 'X')
{
cout<<letter<<endl;
cout<<"this will be written twice for ununderstandable reasons";
letter= cin.get();
cin.ignore();
}
}