C++ Basic I O
C++ provides several ways to perform input and output operations. One of the most common ways is to use the iostream
library, which provides input/output stream classes that can be used to read from or write to the console or other input/output devices.
Here are some examples of basic input/output operations in C++ using the iostream
library:
#include <iostream> int main() { int age; std::cout << "Enter your age: "; std::cin >> age; std::cout << "Your age is: " << age << std::endl; return 0; }
In this example, we first include the iostream
library. We then declare an integer variable age
. We use the std::cout
object to print a message asking the user to enter their age. We use the std::cin
object to read an integer value from the console and store it in the age
variable. Finally, we use std::cout
again to print the value of the age
variable.
Here's another example that demonstrates how to read and write string values:
#include <iostream> #include <string> int main() { std::string name; std::cout << "Enter your name: "; std::getline(std::cin, name); std::cout << "Hello, " << name << "!" << std::endl; return 0; }
In this example, we include the string
header file to use the std::string
class. We declare a string variable name
. We use std::cout
to print a message asking the user to enter their name. We use std::getline()
to read a line of text from the console and store it in the name
variable. Finally, we use std::cout
to print a message that includes the value of the name
variable.
Note that in the second example, we use std::getline()
instead of std::cin
to read a line of text. This is because std::cin
stops reading input as soon as it encounters whitespace (such as a space or a newline character), while std::getline()
reads an entire line of text, including any whitespace.