C++ Standard Input and Output
C++ provides standard input/output streams through the iostream library. cout is used to print output to the console, while cin is used to read input from the user.
Using these streams properly allows you to interact with the user and create dynamic programs.
1. Output Using cout
cout stands for "character output". It sends data to the standard output (usually the screen) and can be chained with the insertion operator <<.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, CodeCrown!" << endl;
cout << "Sum of 5 + 10 = " << (5 + 10) << endl;
return 0;
}
You can chain multiple outputs using << and use endl to move to a new line.
2. Input Using cin
cin stands for "character input". It reads data from the standard input (keyboard) using the extraction operator >>.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You entered: " << age << endl;
return 0;
}
The extraction operator >> reads input until whitespace. For strings with spaces, you can use getline(cin, variable).
3. Formatted Output
You can format output using manipulators from the iomanip library such as setw, setprecision, and fixed.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265;
cout << fixed << setprecision(2);
cout << "Pi rounded to 2 decimal places: " << pi << endl;
cout << setw(10) << 123 << endl; // Right-aligned with width 10
return 0;
}
4. Interactive Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
double height;
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Enter your height (in meters): ";
cin >> height;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Height: " << height << " meters" << endl;
return 0;
}
Conclusion
The cin and cout streams are fundamental in C++ for input and output operations. Using them effectively with manipulators and proper formatting allows you to build interactive and user-friendly programs.
Codecrown