You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Theiostream library provides functionalities for handling input and
output operations in C++.
It includes both wide and narrow character streams for interacting with
data, allowing for flexibility in handling different encodings, such as
single-byte characters (ASCII) and multi-byte characters (UTF-16, UTF-32).
std::cin and std::wcin
std::cin
std::cin is the standard input stream used to read data from the standard
input (usually the keyboard) for narrow character types (char).
Typically, it's used for reading user input in the form of various data types
(e.g., integers, strings).
It waits for user input before processing it and may buffer the input to
optimize performance.
std::wcin
std::wcin is the wide-character equivalent of std::cin, used for reading
wide characters (wchar_t) from standard input. This is useful for reading
internationalized or Unicode data.
It's used to read wide-character data, often necessary for handling non-ASCII
characters or multi-byte encodings.
Similar to std::cin, its input is buffered and processed after the user
types it.
std::cin >> std::boolalpha; allows users to enter the strings "true" and
"false" as input for a boolean variable. Otherwise, std::cin enters a
failure mode and stores a zero value in the boolean variable.
However, when std::boolalpha is enabled for input, numeric values will no
longer be accepted (they evaluate to false and cause std::cin to enter
failure mode).
Enabling std::boolalpha for input will only allow lower-cased false or true
to be accepted. Variations with capital letters will not be accepted. 0 and 1
will also no longer be accepted.
std::cin >> char_var; cannot store a space character into char_var, but
std::cin.get(char_var) can.
std::cint >> std::ws; discards leading whitespace from an input stream.
std::cout and std::wcout
std::cout
std::cout is the standard output stream used for writing data to the
console, typically buffered and using narrow characters (char).
It is used to display output to the user, such as text, numbers, or formatted
data.
Data written to std::cout is stored in memory and written to the console
when the buffer is full or flushed.
Its output can be redirected to a file using the terminal operator >.
When its output is redirected to a file, these messages do not appear on the
terminal.
std::wcout
std::wcout is the wide-character output stream for writing wide characters
(wchar_t) to the console.
It's used for outputting wide-character data, necessary when working with
non-ASCII or multi-byte character sets, such as internationalized text.
Like std::cout, data is buffered before being output to the console.
When outputting floating point numbers, std::cout has a default precision
of 6 -- that is, it assumes all floating point variables are only significant
to 6 digits (the minimum precision of a float), and hence it will truncate
anything after that.
We can override the default precision that std::cout shows by using an
output manipulator function named std::setprecision(). Output manipulators
alter how data is output, and are defined in the iomanip header.
std::cerr and std::wcerr
std::cerr
std::cerr is used for outputting error messages to the standard error
stream (stderr), typically without buffering.
It's commonly used for reporting errors, warnings, or diagnostics.
It ensures that error messages are immediately displayed, regardless of
buffering.
Its output cannot be redirected to a file using the terminal operator
>.
It always prints all messages to the terminal.
std::wcerr
std::wcerr is the wide-character version of std::cerr, used for
outputting error messages in wide-character format (wchar_t).
It's used when you need to output wide-character error messages.
Just like std::cerr, it outputs error messages immediately.
std::endl inserts a newline character (\n) into the output stream and
flushes the stream, ensuring immediate output.
It often used when you need to print a newline and flush the output
immediately (e.g., after displaying a message).
It causes a flush of the output stream, in addition to inserting a newline
character.
std::endl is slightly slower than \n due to additional flushing.
std::ends
std::ends inserts a null character ('\0') into the output stream.
It is commonly used when working with C-style strings, where a null
terminator is needed to mark the end of the string.
It's useful when building strings that need to be null-terminated,
particularly for compatibility with C-style string functions or libraries
that expect a null terminator.
It can be used in conjunction with std::ostringstream or other streams when
constructing such strings.
It does not force a flush of the output buffer.
It simply appends the null character to the stream's content without
affecting the buffer state.
std::flush
std::flush forces the output stream to flush, ensuring any buffered data is
immediately written out, without inserting a newline.
It's used when you want to ensure that all output is immediately written, but
without adding a newline.
It forces a flush of the output stream, but does not insert any characters
into the stream.
Syntax
IOObject << "Message" << std::endl; // Newline and flush
IOObject << "Message" << std::flush; // Flush without newline
std::ostringstream oss;
oss << "Hello, World" << std::ends; // Adds a null character after the text
std::cout << oss.str().c_str(); // Displays the content as a C-style string
<fstream>
Explanation
The <fstream> header in C++ provides classes to perform file-based input
and output operations.
It defines std::ifstream, std::ofstream, and std::fstream, each suited
to specific file handling tasks.
These classes support text and binary I/O and are built on top of the basic
iostream functionality.
std::ifstream, std::ofstream and std::fstream
std::ifstream
std::ifstream is a file input stream class used to read data from files.
It provides input operations similar to std::cin but specifically for file
reading.
It's primarily used to open a file in read mode. Once opened, the file data
can be read line by line or as individual characters.
It uses a buffer to read chunks of data, allowing efficient input operations
by reducing file access time.
It is a non-copyable class.
std::wifstream is the wide-character equivalent of std::ifstream, used to
read data from files.
std::ofstream
std::ofstream is a file output stream class used to write data to files.
It behaves similarly to std::cout but writes output to a file instead of
the console.
It's commonly used to open a file in write mode.
Text and data can be written to the file, either as individual characters or
lines.
It buffers output data for efficient file writing by reducing the number of
write operations.
It is a non-copyable class.
std::wofstream is the wide-character equivalent of std::ofstream, used to
write data to files.
std::fstream
std::fstream is a file stream class that supports both input and output
operations.
It allows reading from and writing to the same file.
Typically, it's used when a file requires both reading and writing.
It can be opened in various modes (read-only, write-only, or both).
It uses a buffer to handle I/O operations efficiently, reducing direct file
access calls.
It is a non-copyable class.
std::wfstream is the wide-character equivalent of std::fstream, providing
both input and output operations.
Declaration Syntax
std::ifstream file;
std::ofstream file;
std::fstream file;
Initialization Syntax
std::ifstream file( "filename.txt" ); // Opens in read mode
traits_type: Traits; the program is ill-formed if Traits::char_type is
not CharT.
int_type: Traits::int_type.
pos_type: Traits::pos_type.
off_type: Traits::off_type.
native_handle_type (C++26): Implementation-defined type that is
TriviallyCopyable and semiregular.
Member Functions
(constructor): Constructs the file stream (public member function).
(destructor) [virtual] (implicitly declared): Destructs the
ifstream/ofstream/fstream and the associated buffer, closes the file (virtual
public member function).
operator=: Moves the file stream (public member function).
swap: Swaps two file streams (public member function).
rdbuf: Returns the underlying raw file device object (public member
function).
native_handle (C++26): Returns the underlying implementation-defined handle
(public member function).
is_open: Checks if the stream has an associated file (public member
function).
open: Opens a file and associates it with the stream (public member
function).
close: Closes the associated file (public member function).
Member Functions Inherited from std::basic_istream (for std::ifstream and std::fstream)
operator>>: Extracts formatted data (public member function of
std::basic_istream< CharT, Traits >).
get: Extracts characters (public member function of
std::basic_istream< CharT, Traits >).
peek: Reads the next character without extracting it (public member
function of std::basic_istream< CharT, Traits >).
unget: Unextracts a character (public member function of
std::basic_istream< CharT, Traits >).
putback: Puts a character into the input stream (public member function of
std::basic_istream< CharT, Traits >).
getline: Extracts characters until the given character is found (public
member function of std::basic_istream< CharT, Traits >).
ignore: Extracts and discards characters until the given character is found
(public member function of std::basic_istream< CharT, Traits >).
read: Extracts blocks of characters (public member function of
std::basic_istream< CharT, Traits >).
readsome: Extracts already available blocks of characters (public member
function of std::basic_istream< CharT, Traits >).
gcount: Returns the number of characters extracted by the last unformatted
input operation (public member function of
std::basic_istream< CharT, Traits >).
tellg: Returns the input position indicator (public member function of
std::basic_istream< CharT, Traits >).
seekg: Sets the input position indicator (public member function of
std::basic_istream< CharT, Traits >).
sync: Synchronizes with the underlying storage device (public member
function of std::basic_istream< CharT, Traits >).
Member Classes Inherited from std::basic_istream (for std::ifstream and std::fstream)
sentry: Implements basic logic for preparation of the stream for input
operations (public member class of std::basic_istream< CharT,Traits >).
Member Functions Inherited from std::basic_istream (for std::ofstream and std::fstream)
operator<<: Inserts formatted data (public member function of
std::basic_ostream< CharT, Traits >).
put: Inserts a character (public member function of
std::basic_ostream< CharT, Traits >).
write: Inserts blocks of characters (public member function of
std::basic_ostream< CharT, Traits >).
tellp: Returns the output position indicator (public member function of
std::basic_ostream< CharT, Traits >).
seekp: Sets the output position indicator (public member function of
std::basic_ostream< CharT, Traits >).
flush: Synchronizes with the underlying storage device (public member
function of std::basic_ostream< CharT, Traits >).
Member Classes Inherited from std::basic_istream (for std::ofstream and std::fstream)
sentry: Implements basic logic for preparation of the stream for output
operations (public member class of std::basic_ostream< CharT,Traits >).
// Used to get the whole line from `std::cin`.std::getline( std::cin >> std::ws, var_name );
// A special case.
#include<iostream>
#include<string>intmain() {
std::cout << "Pick 1 or 2: ";
int choice{};
std::cin >> choice;
std::cout << "Now enter your name: ";
std::string name{};
std::getline( std::cin >> std::ws, name ); // note: added std::ws here.// std::getline( std::cin, name ); // note: no std::ws here, not get what you want.
std::cout << "Hello, " << name << ", you picked " << choice << '\n';
return0;
}
If using std::getline() to read strings, use std::cin >> std::ws input
manipulator to ignore leading whitespace. This needs to be done for each
std::getline() call, as std::ws is not preserved across calls.
When extracting to a variable, the extraction operator (>>) ignores leading
whitespace. It stops extracting when encountering non-leading whitespace.
std::getline() does not ignore leading whitespace. If you want it to ignore
leading whitespace, pass std::cin >> std::ws as the first argument. It
stops extracting when encountering a newline.