C++ Basic Input/Output
1. Output (cout):
The cout object is used to send output to the standard output stream, usually the console. It is part of the iostream library.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
In this example, the << operator is used to send the string "Hello, World!" to the standard output.
2. Input (cin):
The cin object is used to read input from the standard input stream, usually the console. It is also part of the iostream library.
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You entered: " << age << std::endl;
return 0;
}
In this example, the >> operator is used to read an integer value from the standard input and store it in the variable age.
3. Formatting Output:
You can format the output using manipulators, as discussed earlier. For example:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.1415926535;
std::cout << std::fixed << std::setprecision(2) << "Value of pi: " << pi << std::endl;
return 0;
}
This example sets the precision for floating-point output and uses fixed-point notation.
4. Reading and Writing Strings:
#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;
}
Here, getline is used to read a line of text (including spaces) into the string variable name.
5. File I/O:
C++ also supports file input and output using the fstream class.
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile("output.txt");
if (outputFile.is_open()) {
outputFile << "This is a line in the file." << std::endl;
outputFile << "Another line." << std::endl;
outputFile.close();
} else {
std::cerr << "Unable to open the file." << std::endl;
}
return 0;
}
In this example, ofstream is used to create and write to a text file named "output.txt."
These are basic examples of input and output operations in C++. As you progress, you'll encounter more advanced features and techniques, such as error handling, binary file I/O, and custom stream manipulators.