The <iostream>
library provides functionality for input and output in C++. The standard streams provided by this library include cin
, cout
, cerr
, and clog
.
istream
object tied to the standard input (typically the keyboard).ostream
object tied to the standard output (typically the monitor).ostream
object tied to the standard error (typically the monitor), providing unbuffered output.ostream
object tied to the standard error (typically the monitor), providing buffered output.#include <iostream>
#include <iomanip>
int main()
{
char buf[10]{};
std::cin >> std::setw(10) >> buf;
std::cout << "Buffer content: " << buf << '\n';
return 0;
}
cin.get(ch)
: Reads a character from the stream, including whitespace except newline.cin.get(str, 5)
: Reads 4 characters into str
, leaving space for the terminator.getline()
: Extracts newline.gcount()
: Returns the number of characters extracted by the last unformatted input operation.#include <iostream>
int main()
{
char ch;
std::cin.get(ch);
std::cout << "Character read: " << ch << '\n';
char str[5];
std::cin.get(str, 5);
std::cout << "String read: " << str << '\n';
return 0;
}
#include <iostream>
#include <iomanip>
int main()
{
std::cout.setf(std::ios::showpos); // turn on the std::ios::showpos flag
std::cout << 10 << '\n'; // +10
std::cout.unsetf(std::ios::showpos); // turn off the std::ios::showpos flag
std::cout.setf(std::ios::showpos | std::ios::uppercase); // turn on the std::ios::showpos and std::ios::uppercase flag
std::cout << std::hex << 27 << '\n'; // print 27 in hex
return 0;
}
std::hex
, std::dec
, std::oct
: Set the basefield to hexadecimal, decimal, or octal.std::fixed
: Uses decimal notation for floating-point numbers.std::scientific
: Uses scientific notation for floating-point numbers.std::setprecision(int)
: Sets the precision of floating-point numbers.#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::fixed << std::setprecision(2) << 123.456789 << '\n'; // 123.46
std::cout << std::scientific << 123.456789 << '\n'; // 1.234568e+02
std::cout << std::showpoint << 123.0 << '\n'; // 123.000
return 0;
}
std::stringstream
#include <sstream>
#include <iostream>
int main()
{
std::stringstream os;
os << "12345 67.89\n";
std::cout << os.str();
std::string strValue;
os >> strValue; // Read until whitespace
std::cout << "String value: " << strValue << '\n';
int nValue;
double dValue;
os >> nValue >> dValue;
std::cout << "Int value: " << nValue << ", Double value: " << dValue << '\n';
os.str(""); // Erase the buffer
os.clear(); // Reset error flags
return 0;
}
goodbit
: Everything is okay.badbit
: A fatal error occurred.eofbit
: The stream has reached the end of a file.failbit
: A non-fatal error occurred.good()
: Returns true if the goodbit
is set.bad()
: Returns true if the badbit
is set.eof()
: Returns true if the eofbit
is set.fail()
: Returns true if the failbit
is set.clear()
: Clears all flags and restores the stream to the goodbit
state.rdstate()
: Returns the currently set flags.setstate(state)
: Sets the state flag passed in.#include <iostream>
#include <limits>
int main()
{
int num;
while (true)
{
std::cout << "Enter a number: ";
std::cin >> num;
if (std::cin.fail()) // no extraction took place
{
std::cin.clear(); // reset the state bits back to goodbit
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear out the bad input from the stream
std::cout << "Invalid input, please try again.\n";
continue; // try again
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear out any additional input from the stream
break;
}
std::cout << "You entered: " << num << '\n';
return 0;
}
#include <fstream>
#include <iostream>
int main()
{
std::ofstream outf{ "Sample.txt" };
if (!outf)
{
std::cerr << "Uh oh, Sample.txt could not be opened for writing!\n";
return 1;
}
outf << "This is line 1\n";
outf << "This is line 2\n";
return 0;
}
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream file{ "Sample.txt" };
if (!file)
{
std::cerr << "Uh oh, Sample.txt could not be opened for reading!\n";
return 1;
}
std::string strInput;
while (std::getline(file, strInput))
std::cout << strInput << '\n';
return 0;
}
std::ofstream outf{ "file.txt", std::ios::app };
// other method
outf.open("Sample.txt", std::ios::app);
outf.close();
seekg()
: Sets the position of the next input operation.seekp()
: Sets the position of the next output operation.std::ifstream inf{ "Sample.txt" };
inf.seekg(14, std::ios::cur); // move forward 14 bytes
Ios seek flag | Meaning |
---|---|
beg | The offset is relative to the beginning of the file (default) |
cur | The offset is relative to the current location of the file pointer |
end | The offset is relative to the end of the file |
#include <regex>
#include <iostream>
int main()
{
std::string str{ "Hello, World!" };
std::regex re{ R"(\w+)" }; // word characters
std::sregex_iterator begin{ str.begin(), str.end(), re };
std::sregex_iterator end;
for (auto it = begin; it != end; ++it)
std::cout << it->str() << '\n';
return 0;
}
Function | Meaning |
---|---|
std::isalnum(int) |
Returns non-zero if the parameter is a letter or a digit |
std::isalpha(int) |
Returns non-zero if the parameter is a letter |
std::iscntrl(int) |
Returns non-zero if the parameter is a control character |
std::isdigit(int) |
Returns non-zero if the parameter is a digit |
std::isgraph(int) |
Returns non-zero if the parameter is printable character that is not whitespace |
std::isprint(int) |
Returns non-zero if the parameter is printable character (including whitespace) |
std::ispunct(int) |
Returns non-zero if the parameter is neither alphanumeric nor whitespace |
std::isspace(int) |
Returns non-zero if the parameter is whitespace |
std::isxdigit(int) |
Returns non-zero if the parameter is a hexadecimal digit (0-9, a-f, A-F) |
#include <iostream>
#include <cctype>
#include <string>
#include <ranges>
bool isValidName(const std::string& name)
{
return std::ranges::all_of(name, [](char ch) {
return std::isalpha(ch) || std::isspace(ch);
});
}
int main()
{
std::string name{ "John Doe" };
if (isValidName(name))
std::cout << "Valid name\n";
else
std::cout << "Invalid name\n";
return 0;
}
The <iostream>
library provides powerful tools for input and output in C++. Understanding how to use standard streams, file streams, and manipulators is crucial for effective C++ programming.