LearnForFree
C++ For Beginners
Lesson

Input & Output (std::cout, std::cin, std::endl)

C++ handles input and output as streams—continuous flows of bytes moving between your program and external devices like your monitor or keyboard. To use standard streams, you must include <iostream>. • std::cout (Character Output): Sends data from your program out to the console screen. It is paired with the insertion operator (<<), which points data toward cout. You can chain multiple << operators together on one line. • std::cin (Character Input): Reads data typed by the user on the keyboard and stores it inside a variable. It uses the extraction operator (>>), which points data away from cin and into a variable. Note that std::cin stops reading when it hits a space, tab, or Enter key. • std::endl vs. \n: Both move the cursor to a new line. However, std::endl also forces the output buffer to flush (immediately display everything on screen), whereas \n simply inserts a newline character and is slightly faster for heavy printing.
#include <iostream> #include <string> int main() { std::string city; int year; std::cout << "Enter your city: "; std::cin >> city; // Waits for user input std::cout << "Enter the current year: "; std::cin >> year; std::cout << "Greetings from " << city << " in " << year << "!\n"; return 0; }

Watch companion video on YouTube

Sign in to save your progress