Input and output (I/O) operations are fundamental to any programming language. In C++, these operations are handled through streams, providing a flexible and efficient way to interact with users and files.
C++ uses the iostream library to manage input and output. This library defines three standard streams:
The cout
object is used for output. It's typically paired with the insertion operator (<<
) to display text and variables.
#include <iostream>
using namespace std;
int main() {
int age = 25;
cout << "My age is: " << age << endl;
return 0;
}
This example demonstrates how to output a string and an integer variable. The endl
manipulator adds a newline and flushes the output buffer.
For input, C++ uses the cin
object along with the extraction operator (>>
). This allows you to read values from the standard input.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
return 0;
}
This example shows how to read a string and an integer from the user. The program then uses cout
to display the entered information.
C++ provides various manipulators to format output. These are used with the insertion and extraction operators to modify how data is displayed or read.
endl
: Inserts a newline character and flushes the streamsetw(int n)
: Sets the field width for the next input/output operationsetprecision(int n)
: Sets the decimal precision for floating-point valuesfixed
: Uses fixed-point notation for floating-point valuesTo use these manipulators, include the <iomanip>
header.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265359;
cout << fixed << setprecision(2);
cout << "Pi to 2 decimal places: " << pi << endl;
return 0;
}
This example demonstrates how to use manipulators to format the output of a floating-point number.
C++ also supports file input and output operations using the fstream
library. This allows you to read from and write to files, expanding the capabilities of your programs.
For more information on file operations, check out the guide on C++ File I/O Streams.
cerr
for error messages instead of cout
.cout.flush()
to manually flush the output buffer.Understanding I/O operations is crucial for creating interactive C++ programs. As you advance, explore more complex I/O techniques and consider how they integrate with other C++ features like classes and objects for more sophisticated program designs.