-2

Here is a small code:

char a;
while(std::cin >> a) {
    std::cout << a << " is pressed\n";
}

When I type in "w", i get "w is pressed". When I type in "www", i get "w is pressed" 3 times in a row.

Can someone please explain why this happens?

Thanks

Gasim
  • 7,615
  • 14
  • 64
  • 131

3 Answers3

4

When you use std::cin to read a char variable it reads one character at a time. That is why you get 3 iterations in the while loop for input www.

Paul92
  • 8,827
  • 1
  • 23
  • 37
0

There is a queue of inputs. if you entered too much, your input waits in patient...

MeNa
  • 1,467
  • 9
  • 23
0

The first part of the answer is on the first line of your code.

char a;

Variable a is a single char, an 8-bit value typically used to store a code representing a display character. If the display is ASCII, then (value) 0 = no character, (value) 32 = space, value 48 = (character) '0', etc.

std::cin is an instance of class std::istream, it has various members and operator overloads to deal with different types. In the case of a char, you are calling

std::istream::operator(char)

Which reads one char, exactly one, from the input stream and returns.

#include <iostream>
int main()
{
    char a, b, c;
    std::cin >> a >> b >> c;
    std::cout << "a = " << a << ", b = " << b << ", c = " << c << '\n';
    return 0;
}
kfsone
  • 23,617
  • 2
  • 42
  • 74