C++ standard input/output --
library is a header in the C++ standard library for input/output operations.
The following arelibrary's detailed usage instructions, including its main classes and common usage examples.
Main classes
std::istream: Abstract base class for input operations.std::ostream: Abstract base class for output operations.std::iostream: Inherits fromstd::istreamandstd::ostream, used for both input and output operations.std::cin: Standard input stream object, usually associated with the keyboard.std::cout: Standard output stream object, usually associated with the screen.std::cerr: Standard error output stream object, unbuffered, usually associated with the screen.std::clog: Standard log stream object, buffered, usually associated with the screen.
Common operators
>>: Input operator, reads data from the input stream.<<: Output operator, writes data to the output stream.
Basic Usage
Standard input and output:
Example
#include
int
main
(
)
{
int
age
;
std
::
string
name
;
// Use std::cout to output to screen
std
::
cout
<<
"Enter your name: "
;
// Use std::cin to read input from keyboard
std
::
cin
name
;
std
::
cout
<<
"Enter your age: "
;
std
::
cin
age
;
// Output the read data
std
::
cout
<<
"Hello, "
<<
name
<<
"! You are "
<<
age
<<
" years old."
<<
std
::
endl
;
return
0
;
}
Standard error output:
Example
#include
int
main
(
)
{
std
::
cerr
<<
"An error occurred!"
<<
std
::
endl
;
return
0
;
}
Standard log output:
Example
#include
int
main
(
)
{
std
::
clog
<<
"This is a log message."
<<
std
::
endl
;
return
0
;
}
Formatted output:
Uselibrary can format output, such as setting width, precision, and alignment.
Example
#include
#include
int
main
(
)
{
double
pi
=
3.14159
;
// Set output precision
std
::
cout
<<
std
::
setprecision
(
3
)
<<
pi
<<
std
::
endl
;
// Set output width and alignment
std
::
cout
<<
std
::
setw
(
10
)
<<
std
::
left
<<
pi
<<
std
::
endl
;
std
::
cout
<<
std
::
setw
(
10
)
<<
std
::
right
<<
pi
<<
std
::
endl
;
return
0
;
}
Stream state checking:
can check the state of input/output streams to determine whether the operation succeeded.
Example
#include
int
main
(
)
{
int
num
;
std
::
cout
<<
"Enter a number: "
;
std
::
cin
num
;
// Check whether the input operation succeeded
if
(
std
::
cin
.
fail
(
)
)
{
std
::
cerr
<<
"Invalid input!"
<<
std
::
endl
;
}
else
{
std
::
cout
<<
"You entered: "
<<
num
<<
std
::
endl
;
}
return
0
;
}
Processing string input
Usestd::getlineFunctions can read an entire line of input that contains spaces.
Example
#include
#include
int
main
(
)
{
std
::
string
fullName
;
std
::
cout
<<
"Enter your full name: "
;
std
::
getline
(
std
::
cin
, fullName
)
;
std
::
cout
<<
"Hello, "
<<
fullName
<<
"!"
<<
std
::
endl
;
return
0
;
}
The examples above demonstratethe basic usage and common operations of the library, helping you perform input/output handling in C++ programs.