Input and Output Functions in C++
Input Output Functions in C++ cplus
Input and output (I/O) operations are essential for interacting with users. In C++, the iostream library provides cin for input and cout for output. These are part of the standard input/output stream.
coutUsed to display data on the console.
Part of the std namespace.
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
cout << "Sum: " << 10 + 20 << endl;
return 0;
}
Output:
Hello, World!
Sum: 30
Notes:
<< is the insertion operator.
endl inserts a newline.
cinUsed to accept input from the user.
Extracts data from the standard input stream.
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age << " years old." << endl;
return 0;
}
Sample Run:
Enter your age: 25
You are 25 years old.
Notes:
>> is the extraction operator.
Data type of variable must match the expected input.
You can accept multiple values in a single line using cin.
int a, b;
cin >> a >> b;
getline() for Strings
cin stops reading at whitespace.
Use getline() to read full lines with spaces.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your full name: ";
getline(cin, name);
cout << "Hello, " << name << "!" << endl;
return 0;
}
iomanip
Use the <iomanip> library to format output.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265;
cout << fixed << setprecision(2) << pi << endl; // Output: 3.14
return 0;
}
Use cout for output and cin for input.
Use getline() for full-line string input.
Use iomanip for formatted output.
Proper I/O handling is essential for user interaction and debugging.