0

When I type some character this program prints a single message. When I type two characters it prints hello world twice and when aaaaa is typed, five hello world messages are printed and so on! Why?

int _tmain(int argc, _TCHAR* argv[])
{
    char nnn;
    do {
        cout << "hello world" << endl;
        cin >> nnn;
    } while ((nnn != 'y'));

    return 0;
}

Here's a result:

hello world
d
hello world
ffff
hello world
hello world 
hello world
hello world
y
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Joe Martin
  • 11
  • 3
  • 1
    What were you expecting to happen, instead? – dxiv Feb 15 '16 at 21:08
  • i expected it to post only one sentence. – Joe Martin Feb 15 '16 at 21:32
  • You did input 5 non-'y' characters, and the code prints `hello world` for each one (plus one at the very beginning). – dxiv Feb 15 '16 at 21:38
  • so is there another func that i can replace 'cin' with that only reads the input as a whole not one char by one? – Joe Martin Feb 15 '16 at 22:02
  • Not sure if you mean whole words or whole lines. See for example [taking input of a string word by word](http://stackoverflow.com/questions/18318980/taking-input-of-a-string-word-by-word) which has examples of both. – dxiv Feb 15 '16 at 22:15

2 Answers2

3

Because you're reading into char, cin >> nnn; will read one character per iteration, i.e. it goes through all the f's in ffff only because of the loop. It stops and waits for your further input when there is nothing to read.

If you wanted to read the whole word/line at once, you should have used operator>>/std::getline with std::string.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
0

if you input ffff it will consider that you type it four times and will print out "hello world" four times so try to change the char ==> string to avoid this problem.

Selim Ajimi
  • 344
  • 6
  • 21