C++ cin & cout
In this page:
What is cout?
cout is the standard output stream, used with the insertion operator << to send text, numbers, and variable values to the console. It's the tool you reach for any time your program needs to display something to the person running it, from a simple greeting to a computed result.
Example: What is cout?
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
What is cin?
cin is the standard input stream, paired with the extraction operator >> to read whatever the user types and store it in a variable. It automatically converts the typed text into the variable's type, so cin >> age where age is an int will parse the digits the user entered as a number.
Example: What is cin?
#include <iostream>
#include <sstream>
int main() {
std::istringstream cin("25"); // stand-in for real std::cin input
int age;
cin >> age;
std::cout << "Age: " << age << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chaining Output with cout
Chaining several << operators in one statement, like cout << "Sum: " << total << endl;, lets you combine labels and values into one readable line instead of writing separate print statements. This cascading style is idiomatic C++ and keeps output code compact.
Example: Chaining Output with cout
#include <iostream>
int main() {
int total = 42;
std::cout << "Sum: " << total << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Inputs with cin
You can chain >> the same way to read several values in one line, such as cin >> width >> height;, and C++ automatically treats spaces, tabs, and newlines as separators between values. This means the user can type 5 10 or press Enter between numbers and either way works identically.
Example: Multiple Inputs with cin
#include <iostream>
#include <sstream>
int main() {
std::istringstream cin("5 10"); // stand-in for "cin >> width >> height;"
int width, height;
cin >> width >> height;
std::cout << width << " " << height << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
cout with endl and Newline
endl and \n both move output to a new line, but endl additionally flushes the output buffer, forcing any pending data to actually be written to the screen immediately. \n is faster in tight loops since it skips that flush, so many C++ programmers prefer \n for routine output and reserve endl for moments where an immediate flush genuinely matters, like right before a crash or a long-running operation.
Example: cout with endl and Newline
#include <iostream>
int main() {
std::cout << "Flushed immediately" << std::endl;
std::cout << "Faster in tight loops" << "\n";
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: