Input And Output Functions of C++
·
Standard
Input/Output (I/O) library streams functions.
·
Used
for input and output objects.
·
Main
functions are cin, cout, and cerr, etc
Input Function:
cin
- Take
input from the user by the standard input device (keyboard).
- Use the extraction operator (>>) with cin.
Syntax:
cin >> variable;
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
return 0;
}
Output:
Enter your age: 25
Your age is: 25
Output Function:
cout
- Display
output on the standard output device (console).
- Use the insertion operator (<<) with cout.
Syntax:
cout << "Message";
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
Output:
Hello, World!
Error Output
Function: cerr
- Cerr
is used to output error messages.
- Like
cout, it uses the insertion operator (<<), but it outputs to the standard
error stream.
Syntax:
cerr << "Error
message";
Example:
#include <iostream>
using namespace std;
int main() {
cerr << "This is an error message." << endl;
return 0;
}
Output:
This is an error message.
Formatted Input
and Output
setw
·
Part
of the I/O manipulators in the <iomanip> library.
·
Used
to set the width of the output field for the next item displayed using cout.
Example:-
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setw(10) << "Name" << setw(5)
<< "Age" << endl;
cout << setw(10) << "Alice" << setw(5)
<< 25 << endl;
cout << setw(10) << "Bob" << setw(5)
<< 30 << endl;
return 0;
}
Output:
Name
Age
Alice 25
Bob
30
=================================================
0 Comments