How does the CPU know to get data from or send data to a peripheral device?
Keyboard input is handled through an interrupt – a signal sent to the CPU by the motherboard in response to your pressing a key. The CPU maintains a table of functions to call for each type of interrupt, and the operating system sets this so that control passes to it whenever a key is pressed.

The operating system maintains a buffer of pressed keys, and passes on this event to the software currently capturing the keyboard (if any), causing the call of an event handler set by the piece of software. If you run your program from a terminal, then the terminal is the relevant piece of software. It stores the keystrokes in its own buffer, which the C standard library has access to. (In terminal-based operating systems such as DOS or a Unix shell, this is handled by a system call, which is a function executed by the operating system.) The C++ iostream library, which is what your program actually uses, is a wrapper of the C standard library.