SlideShare a Scribd company logo
CS106L
Winter 2007-2008
Handout #03
January 14, 2008
C++ IOStream Library
_________________________________________________________________________________________________________
Introduction
The IOStream library is C++'s way of formatting input and output to a variety of sources, such as the
console, files, or string buffers. However, like most parts of the C++ Standard Library, the IOStream
library has a large number of features and idiosyncrasies that can take some time to adjust to. These first
two lectures serve as an introduction to many features of the streams library and include some very useful
tips and tricks for practical programming.
Stream Manipulators
One of the more powerful features of the C++ IOStream library is its assortment of stream manipulators.
Stream manipulators, declared in the header file <iomanip>, are objects that modify stream properties
while maintaining readability. For example, you're probably familiar with the endl stream manipulator,
which appends a newline to a stream and flushes it to its destination:
cout << "This is some text" << endl;
When you write cout << endl, syntactically, it seems like you're pushing endl into cout just as you
would any other piece of data. Indeed, this is one of the main ideas underlying stream manipulators – that
they should seamlessly blend into normal stream operations.
I've reprinted some of the more useful stream manipulators below:
boolalpha cout << true << endl; // Output: 1
cout << boolalpha << true << endl; // Output: true
Determines whether or not the stream should output boolean values as 1 and 0 or as “true”
and “false.” The opposite manipulator is noboolalpha, which reverses this behavior.
setw(n) cout << 10 << endl; // Output: 10
cout << setw(5) << 10 << endl; // Output: 10 [three spaces, then 10]
Sets the minimum width of the output for the next stream operation. If the data doesn't
meet the minimum field requirement, it is padded with the default fill character until it is
the proper size.
hex, dec, oct cout << 10 << endl; // Output: 10
cout << dec << 10 << endl; // Output: 10
cout << oct << 10 << endl; // Output: 12
cout << hex << 10 << endl; // Output: a
cin >> hex >> x; // Reads a hexadecimal value from the console.
Sets the radix on the stream to either octal (base 8), decimal (base 10), or hexadecimal
(base 16). This can be used either to format output or change the base for input.
ws myStream >> ws >> value;
Skips any whitespace stored in the stream. Useful with getline, as shown later.
When Streams Go Bad
When sending output data to a stream, chances are the operation will succeed. However, when reading
data from an external (or even internal) source it's possible to come across data that doesn't match the
expected format. For example, suppose you open a text file for reading expected to find several integer
values, but instead come across a string. In that case, if your code looks something like:
ifstream in("input.txt");
int value;
for(int i = 0; i < NUM_LINES; i++)
{
in >> value;
// Process 'value' here
}
You will run into trouble because the stream won't know what to do when it encounters invalid data.
Rather than crashing the program or filling the integer with garbage data, instead the stream totally fails
and doesn't change the value of the variable value. Once the stream is in this “error state,” any
subsequent reading or writing operations on it will automatically fail, which can become a big problem.
C++ defines three types of error states: end-of-file state, fail state, and bad state. In an end-of-file (“eof”)
state, the stream reached the end of its input source and was unable to continue reading. In this case, your
program has no more data and should respond appropriately. The bad state is rare and encountered only
during serious I/O errors from which recovery might not be possible (reading from a corrupted file, for
example). In this case, the stream object is most likely unusable and there's not much you can do to fix
the problem.
The fail state is the most common and most vexing of the above error states and results when a stream
tries to read in data that doesn't match the expected formatting. For example, given this code fragment:
cout << "Please enter your age: ";
int age;
cin >> age;
if the user enters something other than a number, for example, “Young,” the stream has no idea what it's
looking at. The line cin >> age is supposed to read in an integer, but the user provided it a string
instead. Instead of filling age in with any value at all, the stream goes into a fail state and doesn't modify
the contents of the integer. Worse, because the stream is in a fail state, any later use of cin to read data
will automatically fail, meaning code you've written in entirely different functions might stop working
properly. Hardly what you wanted!
If a stream is in a fail state, you'll probably want to perform some special handling, possibly by reporting
the error. Once you've fixed any problems, you need to tell the stream that everything is okay. To do
this, use the clear() member function to reset a stream's error flags. Now the stream is back to normal
and I/O operations on it won't automatically fail.
The following table summarizes the member functions you can use to check for error states:
Note: We have not covered the const keyword yet. For now, it's safe to ignore it.
bool good() const if(myStream.good()) { ... no problems ... }
Returns true if there are no errors associated with this stream,
false otherwise. This function is not the opposite of bad().
bool bad() const if(myStream.bad()) { ... serious I/O error ... }
Returns true if a serious I/O error occurred on the stream, false
otherwise. If this function returns true, the stream may be
entirely invalid. This function is not the opposite of good().
bool fail() const
operator ! const
if(myStream.fail()) { ... I/O operation failed ... }
if(!myStream) { ... I/O operation failed ... }
Returns true if a stream operation has failed that wasn't caused by
reaching the end of the file, false otherwise. Unlike an error
signaled by bad(), it's usually possible to recover from an error
signaled by fail().
bool eof() const if(myStream.eof()) { ... hit the end of the file ... }
Returns whether the stream has reached the end of the file.
void clear() myStream.clear(); // Stream is now valid.
Clears any associated error states on the stream. If the stream is in
an error state that is recoverable, make sure to call clear() to
remove the error state before proceeding.
When Streams Do Too Much
Suppose you have the following code fragment:
int age;
double hourlyWage;
cout << "Please enter your age: ";
cin >> age;
cout << "Please enter your hourly wage: ";
cin >> hourlyWage;
As mentioned above, if the user enters a string or otherwise non-integer value when prompted for their
age, the stream will go into a fail state. But what if the user provides too much information? For
example, suppose the input is 2.71828. You would expect that, since this isn't an integer (it's a real
number), the stream would go into an automatic fail state. However, this isn't quite what happens. The
first call, cin >> age, will fill the value of age in with 2. The next call, cin >> hourlyWage, rather
than prompting the user, will find the value .71828 from the earlier input and fill in hourlyWage with
that information. Essentially, the stream stored too much information (or, rather, you didn't take out
enough). As if this wasn't bad enough, suppose you had this program instead:
string password, char yesOrNo;
cout << "Enter administrator password: ";
cin >> password;
if(password == "Bubba")
{
cout << "Do you want to erase your hard drive (Y or N)? ";
cin >> yesOrNo;
if(yesOrNo == 'y')
EraseHardDrive();
}
If the password is “Bubba,” what happens if someone enters Bubba y as the password? The first call,
cin >> password, will only pull out Bubba from the stream. Once you reach the second cin call, it
automatically fills it in with the leftover y, and oh dear, there goes your hard drive! Clearly this is not
what you want to do.
As you can see, reading directly from cin can be a real hassle and almost seems to pose more problems
than it solves. This is the reason that in CS106B and CS106X we provide you the simpio.h library – so
you don't have to deal with these sorts of errors in your programs. In the next section, we'll explore an
entirely different way of reading input from the console that bypasses most of the above problems.
getline
The getline function is truly wonderful. It lets you read in an entire line of text as a single string.
When used for file input, it provides an easy way to get all the data on a line without advance knowledge
of the formatting. Used on the cin stream, it guarantees a way to read input without the possibility that
the user left extra characters in cin that might get read later.
For example, to read a multiword string from the console, you could use this code:
string myStr;
getline(cin, myStr);
No matter how many words or tokens the user types on this line, because getline reads until it
encounters a newline, all of the data will be absorbed and stored in the string. No longer do you need to
worry about strange I/O edge cases!
However, getline does have a small problem when mixed with regular cin operations with the stream
extraction operator >>. When the user presses return after entering text in response to a cin prompt, the
newline character is stored in the cin internal buffer. Normally, whenever you try to extract data from a
stream using operator >>, the stream passes over all newline and whitespace characters before reading
meaningful data. This means that if you write code like this:
int dummyInt;
cin >> dummyInt;
cin >> dummyInt;
The newline stored in cin after the user enters a value for dummyInt is eaten by cin before the second
value of dummyInt is read in. However, if we replace the second call to cin with a call to getline, as
shown here:
int dummyInt;
string dummyString;
cin >> dummyInt;
getline(cin, dummyString);
The getline function will always return an empty string. Why? Because unlike a regular cin
statement, getline does not skip over the whitespace still remaining in the cin stream. Consequently,
as soon as getline is called, it will find the newline left over from the previous cin statement, assume
the user has pressed return, and return the empty string.
There are two main ways to fix this. First, you can use the ws (whitespace) stream manipulator to remove
all the whitespace from cin, as shown here:
int dummyInt;
string dummyString;
cin >> dummyInt >> ws; // Now works the way you'd expect it to, mostly...
getline(cin, dummyString);
While this works well, it is not necessarily the optimal solution because the user might have filled cin
with additional garbage data in the cin call that will fill dummyString with information before the user
has a chance to respond. The better option, and the one the CS106 libraries use, is to replace all normal
stream extraction operations using cin with calls to library functions like GetInteger and GetLine
that accomplish the same thing. Fortunately, with the information in the next section, you'll be able to
write GetInteger and almost any Get____ function you'd ever need to use.
stringstream
Before we discuss writing GetInteger, we'll need to take a diversion to another type of C++ stream.
Often you will need to construct a string composed both of plain text and numeric or other data. For
example, suppose you wanted to call this function:
void MessageBoxAlert(string message);
and have it display a message box to the user informing them that the level number they wanted to warp
to is out of bounds. At first thought, you might try something like
int levelNum; // Initialized, out of bounds.
MessageBoxAlert("Level " + levelNum + " is out of bounds."); // ERROR
For those of you with Java experience this might seem natural, but in C++ this isn't legal because you
can't add numbers to strings (and when you can, it's almost certainly won't do what you expected). To fix
this, you can use a stringstream, a stream object that stores its data in a growing string buffer. You
could, for example, do this:
int levelNum; // Initialized, out of bounds.
stringstream messageText;
messageText << "Level " << levelNum << " is out of bounds.";
MessageBoxAlert(messageText.str());
Except for the last line, most of what is going on here should be self explanatory. You're creating an
object of type stringstream and filling it in with formatted data. In the last line, you call the str()
member function to get the string the stringstream object has built for you.
Just as you can use stringstreams to build strings from data, you can also use them to extract
formatted data from string input. For example:
stringstream myConverter;
int myInt;
string myString;
double myDouble;
myConverter << "137 Hello 2.71828"; // Fill in string data
myConverter >> myInt >> myString >> myDouble; // Extract mixed data!
As with all streams, you can use stream manipulators on stringstreams to format the source data, and
if you try to extract data of the wrong type from a stringstream the stream will go into a fail state.
stringstreams are especially useful in conjunction with getline. To read in an object of any type,
you can call getline to read a line of text from the console, guaranteeing that nothing is left over in
cin, then pass the string into a stringstream to format and extract the data. If the data isn't well-
formatted, when you try to extract formatted data the stream will go into failure mode and you can report
an error. Similarly, if after you read data from the stringstream the stream has any remaining contents
(one way to check this is to see if you can read a char out of the stringstream successfully), you can
report to the user that they've entered too much. In fact, this is exactly how the CS106 library function
GetInteger works!
More To Explore
C++ streams are extremely powerful and encompass a huge amount of functionality. While there are
many more facets to explore, I highly recommending exploring some of these topics:
• Random Access: Many data files store multiple pieces of information in contiguous blocks. For
example, a ZIP archive containing a directory structure most likely stores each compressed file at
a different offset from the start of the file. Thus, if you wanted to write a program capable of
extracting a single file from the archive, you'd almost certainly need the ability to jump to
arbitrary locations in a file. C++ IOStreams support this functionality with the seekg, tellg,
seekp, and tellp functions (the first two for istreams, the latter for ostreams). Random
access lets you quickly jump to single records in large data blocks and can be useful in data file
design.
• read and write: When you write numeric data to a stream, you're actually converting them into
sequences of characters that represent those numbers. For example, when you print out the four-
byte value 78979871, you're using eight bytes to represent the data on screen or in a file. These
extra bytes can quickly add up, and it's actually possible to have on-disk representations of data
that are more than twice as large as the data stored in RAM. To get around this, C++ IOStreams
let you directly write data from RAM onto disk without any formatting. All ostreams support
the write function that writes unformatted data to a stream, and istreams support read to read
unformatted data from a stream into memory. When used well, these functions can cut file
loading times and reduce disk space usage. For example, The CS106 Lexicon class uses read
to quickly load its data file into memory.
Practice Questions
Don't worry, I'm not going to collect and grade these questions. However, I highly encourage you to try
them out. It's one thing to see the IOStream library worked out in front of you, but it's a whole other thing
to try to make it work for you!
1. Write a function ExtractFirstToken that accepts a string and returns the first token from that
string. For example, if you passed in the string “Eleanor Roosevelt,” the function should return
“Eleanor.” For our purposes, define a token as a single continuous block of characters with no
intervening whitespace. While it's possible to write this using the C library function isspace
and a for loop, there's a much shorter solution leveraging off of a stringstream.
2. Write a function HasHexLetters that accepts an int and returns whether or not that integer's
hexadecimal representation contains letters. (Hint: you'll need to use the hex and dec stream
manipulators in conjunction with a stringstream. Try to solve this problem without brute-
forcing it: leverage off the streams library instead of using for loops.)
3. Using the code for GetInteger we covered in class and the boolalpha stream manipulator,
write a function GetBoolean that waits for the user to enter “true” or “false” and returns the
value.
Quick Reference: Simplified IOStream Hierarchy
ios
good
bad
eof
fail
clear
istream ostream
iostream
>>
get
peek
read
seekg
tellg
<<
put
write
seekp
tellp
ifstream ofstreamfstream
open
is_open
ostringstreamstringstreamistringstream
str
open
is_open
open
is_open
strstr
File Streams
String Streams
cin cout
width
fill
precision

More Related Content

What's hot

Analyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectAnalyzing the Dolphin-emu project
Analyzing the Dolphin-emu project
PVS-Studio
 
C++ io manipulation
C++ io manipulationC++ io manipulation
C++ io manipulation
Pedro Hugo Valencia Morales
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
kimberly_Bm10203
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
Ekaterina Milovidova
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
Bartlomiej Filipek
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
Carson Wilber
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
Bartlomiej Filipek
 
What comments hide
What comments hideWhat comments hide
What comments hide
PVS-Studio
 
Analysis of the Trans-Proteomic Pipeline (TPP) project
Analysis of the Trans-Proteomic Pipeline (TPP) projectAnalysis of the Trans-Proteomic Pipeline (TPP) project
Analysis of the Trans-Proteomic Pipeline (TPP) project
PVS-Studio
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Andrey Karpov
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
Geeks Anonymes
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerRechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Andrey Karpov
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PVS-Studio
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
archikabhatia
 
Managing console input
Managing console inputManaging console input
Managing console input
rajshreemuthiah
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programming
Larion
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
CyberPlusIndia
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
Programming Homework Help
 

What's hot (20)

Analyzing the Dolphin-emu project
Analyzing the Dolphin-emu projectAnalyzing the Dolphin-emu project
Analyzing the Dolphin-emu project
 
C++ io manipulation
C++ io manipulationC++ io manipulation
C++ io manipulation
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
 
What comments hide
What comments hideWhat comments hide
What comments hide
 
Analysis of the Trans-Proteomic Pipeline (TPP) project
Analysis of the Trans-Proteomic Pipeline (TPP) projectAnalysis of the Trans-Proteomic Pipeline (TPP) project
Analysis of the Trans-Proteomic Pipeline (TPP) project
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerRechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programming
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
 

Viewers also liked

Excursión a taramundi
Excursión a taramundiExcursión a taramundi
Excursión a taramundi
isabelri
 
Filozofia ewolucji (kwantów)
Filozofia ewolucji (kwantów)Filozofia ewolucji (kwantów)
Filozofia ewolucji (kwantów)
kwantologia2
 
Preference verbs
Preference verbsPreference verbs
Preference verbs
javierusieto
 
11 vidu baitap_c
11 vidu baitap_c11 vidu baitap_c
11 vidu baitap_cHồ Lợi
 
Phân tích một số thuật toán
Phân tích một số thuật toánPhân tích một số thuật toán
Phân tích một số thuật toán
Hồ Lợi
 
Diferencias de webs
Diferencias de websDiferencias de webs
Diferencias de webs
irenepereez99
 
12 vidu baitap_c
12 vidu baitap_c12 vidu baitap_c
12 vidu baitap_cHồ Lợi
 
Sandler asia introduction dec 2015
Sandler asia introduction dec 2015Sandler asia introduction dec 2015
Sandler asia introduction dec 2015
Joseph Palumbo,MBA JPalumbo@ust.hk
 
MICE info - engl
MICE info - englMICE info - engl
MICE info - engl
Natalia Martyshkina
 
Geochemical Analysis of Soils, Marine Sediments, and Peat by Shannon lee
Geochemical Analysis of Soils, Marine Sediments, and Peat by Shannon leeGeochemical Analysis of Soils, Marine Sediments, and Peat by Shannon lee
Geochemical Analysis of Soils, Marine Sediments, and Peat by Shannon lee
Trinity College Dublin
 
La Ley de la Atracción y las Claves del Triunfo
La  Ley de la Atracción y las Claves del TriunfoLa  Ley de la Atracción y las Claves del Triunfo
La Ley de la Atracción y las Claves del Triunfo
Douglas Saito Melo
 
Noticia para el aula Bansky Siria
 Noticia para el aula Bansky Siria Noticia para el aula Bansky Siria
Noticia para el aula Bansky Siria
Miriam Leiros
 
Gemba Walk 201
Gemba Walk 201Gemba Walk 201
Gemba Walk 201
Creative Safety Supply
 
Αυτός ο κόσμος ο μικρός ο μέγας
Αυτός ο κόσμος ο μικρός ο μέγαςΑυτός ο κόσμος ο μικρός ο μέγας
Αυτός ο κόσμος ο μικρός ο μέγας
Sofoklis Sotiriou
 
біла о.о. формування професійної компетентності творчого педагога
біла о.о.  формування професійної  компетентності творчого педагогабіла о.о.  формування професійної  компетентності творчого педагога
біла о.о. формування професійної компетентності творчого педагога
Ольга Рябошапка
 
Long term fiscal sustainability - Aziz Aluthman, Qatar
Long term fiscal sustainability - Aziz Aluthman, QatarLong term fiscal sustainability - Aziz Aluthman, Qatar
Long term fiscal sustainability - Aziz Aluthman, Qatar
OECD Governance
 
Key to voltammetry exercise
Key to voltammetry exerciseKey to voltammetry exercise
Key to voltammetry exercise
Pipat Chooto
 
Patronage 2016 Windows 10 Warsztaty
Patronage 2016 Windows 10 WarsztatyPatronage 2016 Windows 10 Warsztaty
Patronage 2016 Windows 10 Warsztaty
intive
 
Homeostasis Panel Revision Guide
Homeostasis Panel Revision GuideHomeostasis Panel Revision Guide
Homeostasis Panel Revision Guide
meducationdotnet
 
Key ex eg cou
Key ex eg couKey ex eg cou
Key ex eg cou
Pipat Chooto
 

Viewers also liked (20)

Excursión a taramundi
Excursión a taramundiExcursión a taramundi
Excursión a taramundi
 
Filozofia ewolucji (kwantów)
Filozofia ewolucji (kwantów)Filozofia ewolucji (kwantów)
Filozofia ewolucji (kwantów)
 
Preference verbs
Preference verbsPreference verbs
Preference verbs
 
11 vidu baitap_c
11 vidu baitap_c11 vidu baitap_c
11 vidu baitap_c
 
Phân tích một số thuật toán
Phân tích một số thuật toánPhân tích một số thuật toán
Phân tích một số thuật toán
 
Diferencias de webs
Diferencias de websDiferencias de webs
Diferencias de webs
 
12 vidu baitap_c
12 vidu baitap_c12 vidu baitap_c
12 vidu baitap_c
 
Sandler asia introduction dec 2015
Sandler asia introduction dec 2015Sandler asia introduction dec 2015
Sandler asia introduction dec 2015
 
MICE info - engl
MICE info - englMICE info - engl
MICE info - engl
 
Geochemical Analysis of Soils, Marine Sediments, and Peat by Shannon lee
Geochemical Analysis of Soils, Marine Sediments, and Peat by Shannon leeGeochemical Analysis of Soils, Marine Sediments, and Peat by Shannon lee
Geochemical Analysis of Soils, Marine Sediments, and Peat by Shannon lee
 
La Ley de la Atracción y las Claves del Triunfo
La  Ley de la Atracción y las Claves del TriunfoLa  Ley de la Atracción y las Claves del Triunfo
La Ley de la Atracción y las Claves del Triunfo
 
Noticia para el aula Bansky Siria
 Noticia para el aula Bansky Siria Noticia para el aula Bansky Siria
Noticia para el aula Bansky Siria
 
Gemba Walk 201
Gemba Walk 201Gemba Walk 201
Gemba Walk 201
 
Αυτός ο κόσμος ο μικρός ο μέγας
Αυτός ο κόσμος ο μικρός ο μέγαςΑυτός ο κόσμος ο μικρός ο μέγας
Αυτός ο κόσμος ο μικρός ο μέγας
 
біла о.о. формування професійної компетентності творчого педагога
біла о.о.  формування професійної  компетентності творчого педагогабіла о.о.  формування професійної  компетентності творчого педагога
біла о.о. формування професійної компетентності творчого педагога
 
Long term fiscal sustainability - Aziz Aluthman, Qatar
Long term fiscal sustainability - Aziz Aluthman, QatarLong term fiscal sustainability - Aziz Aluthman, Qatar
Long term fiscal sustainability - Aziz Aluthman, Qatar
 
Key to voltammetry exercise
Key to voltammetry exerciseKey to voltammetry exercise
Key to voltammetry exercise
 
Patronage 2016 Windows 10 Warsztaty
Patronage 2016 Windows 10 WarsztatyPatronage 2016 Windows 10 Warsztaty
Patronage 2016 Windows 10 Warsztaty
 
Homeostasis Panel Revision Guide
Homeostasis Panel Revision GuideHomeostasis Panel Revision Guide
Homeostasis Panel Revision Guide
 
Key ex eg cou
Key ex eg couKey ex eg cou
Key ex eg cou
 

Similar to 030 cpp streams

INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
jaggernaoma
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequences
ssuserf86fba
 
2 data and c
2 data and c2 data and c
2 data and c
MomenMostafa
 
C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environment
snchnchl
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
Ajenkris Kungkung
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
gerrell
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
aprilyyy
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
JamaicaAubreyUnite
 
THE IO LIBRARY in C++
THE IO LIBRARY in C++THE IO LIBRARY in C++
THE IO LIBRARY in C++
Prof Ansari
 
data.txtInternational Business Management l2 Cons.docx
data.txtInternational Business Management       l2        Cons.docxdata.txtInternational Business Management       l2        Cons.docx
data.txtInternational Business Management l2 Cons.docx
theodorelove43763
 
The free lunch is over
The free lunch is overThe free lunch is over
The free lunch is over
Thadeu Russo
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
ppd1961
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020
Nikos Mouzakitis
 
Lesson 2 starting output
Lesson 2 starting outputLesson 2 starting output
Lesson 2 starting output
WayneJones104
 
My final requirement
My final requirementMy final requirement
My final requirement
katrinaguevarra29
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lesson
slantsixgames
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
Princess Sam
 

Similar to 030 cpp streams (20)

INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequences
 
2 data and c
2 data and c2 data and c
2 data and c
 
C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environment
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
THE IO LIBRARY in C++
THE IO LIBRARY in C++THE IO LIBRARY in C++
THE IO LIBRARY in C++
 
data.txtInternational Business Management l2 Cons.docx
data.txtInternational Business Management       l2        Cons.docxdata.txtInternational Business Management       l2        Cons.docx
data.txtInternational Business Management l2 Cons.docx
 
The free lunch is over
The free lunch is overThe free lunch is over
The free lunch is over
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020
 
Lesson 2 starting output
Lesson 2 starting outputLesson 2 starting output
Lesson 2 starting output
 
My final requirement
My final requirementMy final requirement
My final requirement
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lesson
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
 

More from Hồ Lợi

Tóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của cTóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của cHồ Lợi
 
Lect04 functions
Lect04 functionsLect04 functions
Lect04 functionsHồ Lợi
 
Ky thuatkhudequy
Ky thuatkhudequyKy thuatkhudequy
Ky thuatkhudequyHồ Lợi
 
Itt epc assignment
Itt epc assignmentItt epc assignment
Itt epc assignmentHồ Lợi
 
Huong danontapc
Huong danontapcHuong danontapc
Huong danontapcHồ Lợi
 
H hai epc_baitap
H hai epc_baitapH hai epc_baitap
H hai epc_baitapHồ Lợi
 
Giaotrinhbaitapkythuatlaptrinh
GiaotrinhbaitapkythuatlaptrinhGiaotrinhbaitapkythuatlaptrinh
GiaotrinhbaitapkythuatlaptrinhHồ Lợi
 
Giao trinh ky thuat lap trinh 2
Giao trinh ky thuat lap trinh 2Giao trinh ky thuat lap trinh 2
Giao trinh ky thuat lap trinh 2Hồ Lợi
 
Giao trinh c c++
Giao trinh c c++Giao trinh c c++
Giao trinh c c++Hồ Lợi
 
Epc assignment
Epc assignmentEpc assignment
Epc assignment
Hồ Lợi
 
Epc test practical
Epc test practicalEpc test practical
Epc test practical
Hồ Lợi
 
De thic++ --th
De thic++ --thDe thic++ --th
De thic++ --thHồ Lợi
 

More from Hồ Lợi (20)

Xu ly chuoi
Xu ly chuoiXu ly chuoi
Xu ly chuoi
 
Tóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của cTóm tắt các hàm chuẩn của c
Tóm tắt các hàm chuẩn của c
 
T4
T4T4
T4
 
Nguyen lyoop
Nguyen lyoopNguyen lyoop
Nguyen lyoop
 
Lect04 functions
Lect04 functionsLect04 functions
Lect04 functions
 
Ky thuatkhudequy
Ky thuatkhudequyKy thuatkhudequy
Ky thuatkhudequy
 
Itt epc assignment
Itt epc assignmentItt epc assignment
Itt epc assignment
 
Huong danontapc
Huong danontapcHuong danontapc
Huong danontapc
 
H hai epc_baitap
H hai epc_baitapH hai epc_baitap
H hai epc_baitap
 
Gtrinh oop
Gtrinh oopGtrinh oop
Gtrinh oop
 
Giaotrinhbaitapkythuatlaptrinh
GiaotrinhbaitapkythuatlaptrinhGiaotrinhbaitapkythuatlaptrinh
Giaotrinhbaitapkythuatlaptrinh
 
Giao trinh ky thuat lap trinh 2
Giao trinh ky thuat lap trinh 2Giao trinh ky thuat lap trinh 2
Giao trinh ky thuat lap trinh 2
 
Giao trinh c c++
Giao trinh c c++Giao trinh c c++
Giao trinh c c++
 
File trong c_
File trong c_File trong c_
File trong c_
 
Epc assignment
Epc assignmentEpc assignment
Epc assignment
 
Epc test practical
Epc test practicalEpc test practical
Epc test practical
 
De thic++ --th
De thic++ --thDe thic++ --th
De thic++ --th
 
Dethi c++ -lt
Dethi c++ -ltDethi c++ -lt
Dethi c++ -lt
 
Debug trong c
Debug trong cDebug trong c
Debug trong c
 
D05 stl
D05 stlD05 stl
D05 stl
 

030 cpp streams

  • 1. CS106L Winter 2007-2008 Handout #03 January 14, 2008 C++ IOStream Library _________________________________________________________________________________________________________ Introduction The IOStream library is C++'s way of formatting input and output to a variety of sources, such as the console, files, or string buffers. However, like most parts of the C++ Standard Library, the IOStream library has a large number of features and idiosyncrasies that can take some time to adjust to. These first two lectures serve as an introduction to many features of the streams library and include some very useful tips and tricks for practical programming. Stream Manipulators One of the more powerful features of the C++ IOStream library is its assortment of stream manipulators. Stream manipulators, declared in the header file <iomanip>, are objects that modify stream properties while maintaining readability. For example, you're probably familiar with the endl stream manipulator, which appends a newline to a stream and flushes it to its destination: cout << "This is some text" << endl; When you write cout << endl, syntactically, it seems like you're pushing endl into cout just as you would any other piece of data. Indeed, this is one of the main ideas underlying stream manipulators – that they should seamlessly blend into normal stream operations. I've reprinted some of the more useful stream manipulators below: boolalpha cout << true << endl; // Output: 1 cout << boolalpha << true << endl; // Output: true Determines whether or not the stream should output boolean values as 1 and 0 or as “true” and “false.” The opposite manipulator is noboolalpha, which reverses this behavior. setw(n) cout << 10 << endl; // Output: 10 cout << setw(5) << 10 << endl; // Output: 10 [three spaces, then 10] Sets the minimum width of the output for the next stream operation. If the data doesn't meet the minimum field requirement, it is padded with the default fill character until it is the proper size. hex, dec, oct cout << 10 << endl; // Output: 10 cout << dec << 10 << endl; // Output: 10 cout << oct << 10 << endl; // Output: 12 cout << hex << 10 << endl; // Output: a cin >> hex >> x; // Reads a hexadecimal value from the console. Sets the radix on the stream to either octal (base 8), decimal (base 10), or hexadecimal (base 16). This can be used either to format output or change the base for input. ws myStream >> ws >> value; Skips any whitespace stored in the stream. Useful with getline, as shown later.
  • 2. When Streams Go Bad When sending output data to a stream, chances are the operation will succeed. However, when reading data from an external (or even internal) source it's possible to come across data that doesn't match the expected format. For example, suppose you open a text file for reading expected to find several integer values, but instead come across a string. In that case, if your code looks something like: ifstream in("input.txt"); int value; for(int i = 0; i < NUM_LINES; i++) { in >> value; // Process 'value' here } You will run into trouble because the stream won't know what to do when it encounters invalid data. Rather than crashing the program or filling the integer with garbage data, instead the stream totally fails and doesn't change the value of the variable value. Once the stream is in this “error state,” any subsequent reading or writing operations on it will automatically fail, which can become a big problem. C++ defines three types of error states: end-of-file state, fail state, and bad state. In an end-of-file (“eof”) state, the stream reached the end of its input source and was unable to continue reading. In this case, your program has no more data and should respond appropriately. The bad state is rare and encountered only during serious I/O errors from which recovery might not be possible (reading from a corrupted file, for example). In this case, the stream object is most likely unusable and there's not much you can do to fix the problem. The fail state is the most common and most vexing of the above error states and results when a stream tries to read in data that doesn't match the expected formatting. For example, given this code fragment: cout << "Please enter your age: "; int age; cin >> age; if the user enters something other than a number, for example, “Young,” the stream has no idea what it's looking at. The line cin >> age is supposed to read in an integer, but the user provided it a string instead. Instead of filling age in with any value at all, the stream goes into a fail state and doesn't modify the contents of the integer. Worse, because the stream is in a fail state, any later use of cin to read data will automatically fail, meaning code you've written in entirely different functions might stop working properly. Hardly what you wanted! If a stream is in a fail state, you'll probably want to perform some special handling, possibly by reporting the error. Once you've fixed any problems, you need to tell the stream that everything is okay. To do this, use the clear() member function to reset a stream's error flags. Now the stream is back to normal and I/O operations on it won't automatically fail.
  • 3. The following table summarizes the member functions you can use to check for error states: Note: We have not covered the const keyword yet. For now, it's safe to ignore it. bool good() const if(myStream.good()) { ... no problems ... } Returns true if there are no errors associated with this stream, false otherwise. This function is not the opposite of bad(). bool bad() const if(myStream.bad()) { ... serious I/O error ... } Returns true if a serious I/O error occurred on the stream, false otherwise. If this function returns true, the stream may be entirely invalid. This function is not the opposite of good(). bool fail() const operator ! const if(myStream.fail()) { ... I/O operation failed ... } if(!myStream) { ... I/O operation failed ... } Returns true if a stream operation has failed that wasn't caused by reaching the end of the file, false otherwise. Unlike an error signaled by bad(), it's usually possible to recover from an error signaled by fail(). bool eof() const if(myStream.eof()) { ... hit the end of the file ... } Returns whether the stream has reached the end of the file. void clear() myStream.clear(); // Stream is now valid. Clears any associated error states on the stream. If the stream is in an error state that is recoverable, make sure to call clear() to remove the error state before proceeding. When Streams Do Too Much Suppose you have the following code fragment: int age; double hourlyWage; cout << "Please enter your age: "; cin >> age; cout << "Please enter your hourly wage: "; cin >> hourlyWage; As mentioned above, if the user enters a string or otherwise non-integer value when prompted for their age, the stream will go into a fail state. But what if the user provides too much information? For example, suppose the input is 2.71828. You would expect that, since this isn't an integer (it's a real number), the stream would go into an automatic fail state. However, this isn't quite what happens. The first call, cin >> age, will fill the value of age in with 2. The next call, cin >> hourlyWage, rather than prompting the user, will find the value .71828 from the earlier input and fill in hourlyWage with that information. Essentially, the stream stored too much information (or, rather, you didn't take out enough). As if this wasn't bad enough, suppose you had this program instead:
  • 4. string password, char yesOrNo; cout << "Enter administrator password: "; cin >> password; if(password == "Bubba") { cout << "Do you want to erase your hard drive (Y or N)? "; cin >> yesOrNo; if(yesOrNo == 'y') EraseHardDrive(); } If the password is “Bubba,” what happens if someone enters Bubba y as the password? The first call, cin >> password, will only pull out Bubba from the stream. Once you reach the second cin call, it automatically fills it in with the leftover y, and oh dear, there goes your hard drive! Clearly this is not what you want to do. As you can see, reading directly from cin can be a real hassle and almost seems to pose more problems than it solves. This is the reason that in CS106B and CS106X we provide you the simpio.h library – so you don't have to deal with these sorts of errors in your programs. In the next section, we'll explore an entirely different way of reading input from the console that bypasses most of the above problems. getline The getline function is truly wonderful. It lets you read in an entire line of text as a single string. When used for file input, it provides an easy way to get all the data on a line without advance knowledge of the formatting. Used on the cin stream, it guarantees a way to read input without the possibility that the user left extra characters in cin that might get read later. For example, to read a multiword string from the console, you could use this code: string myStr; getline(cin, myStr); No matter how many words or tokens the user types on this line, because getline reads until it encounters a newline, all of the data will be absorbed and stored in the string. No longer do you need to worry about strange I/O edge cases! However, getline does have a small problem when mixed with regular cin operations with the stream extraction operator >>. When the user presses return after entering text in response to a cin prompt, the newline character is stored in the cin internal buffer. Normally, whenever you try to extract data from a stream using operator >>, the stream passes over all newline and whitespace characters before reading meaningful data. This means that if you write code like this: int dummyInt; cin >> dummyInt; cin >> dummyInt; The newline stored in cin after the user enters a value for dummyInt is eaten by cin before the second value of dummyInt is read in. However, if we replace the second call to cin with a call to getline, as shown here:
  • 5. int dummyInt; string dummyString; cin >> dummyInt; getline(cin, dummyString); The getline function will always return an empty string. Why? Because unlike a regular cin statement, getline does not skip over the whitespace still remaining in the cin stream. Consequently, as soon as getline is called, it will find the newline left over from the previous cin statement, assume the user has pressed return, and return the empty string. There are two main ways to fix this. First, you can use the ws (whitespace) stream manipulator to remove all the whitespace from cin, as shown here: int dummyInt; string dummyString; cin >> dummyInt >> ws; // Now works the way you'd expect it to, mostly... getline(cin, dummyString); While this works well, it is not necessarily the optimal solution because the user might have filled cin with additional garbage data in the cin call that will fill dummyString with information before the user has a chance to respond. The better option, and the one the CS106 libraries use, is to replace all normal stream extraction operations using cin with calls to library functions like GetInteger and GetLine that accomplish the same thing. Fortunately, with the information in the next section, you'll be able to write GetInteger and almost any Get____ function you'd ever need to use. stringstream Before we discuss writing GetInteger, we'll need to take a diversion to another type of C++ stream. Often you will need to construct a string composed both of plain text and numeric or other data. For example, suppose you wanted to call this function: void MessageBoxAlert(string message); and have it display a message box to the user informing them that the level number they wanted to warp to is out of bounds. At first thought, you might try something like int levelNum; // Initialized, out of bounds. MessageBoxAlert("Level " + levelNum + " is out of bounds."); // ERROR For those of you with Java experience this might seem natural, but in C++ this isn't legal because you can't add numbers to strings (and when you can, it's almost certainly won't do what you expected). To fix this, you can use a stringstream, a stream object that stores its data in a growing string buffer. You could, for example, do this: int levelNum; // Initialized, out of bounds. stringstream messageText; messageText << "Level " << levelNum << " is out of bounds."; MessageBoxAlert(messageText.str());
  • 6. Except for the last line, most of what is going on here should be self explanatory. You're creating an object of type stringstream and filling it in with formatted data. In the last line, you call the str() member function to get the string the stringstream object has built for you. Just as you can use stringstreams to build strings from data, you can also use them to extract formatted data from string input. For example: stringstream myConverter; int myInt; string myString; double myDouble; myConverter << "137 Hello 2.71828"; // Fill in string data myConverter >> myInt >> myString >> myDouble; // Extract mixed data! As with all streams, you can use stream manipulators on stringstreams to format the source data, and if you try to extract data of the wrong type from a stringstream the stream will go into a fail state. stringstreams are especially useful in conjunction with getline. To read in an object of any type, you can call getline to read a line of text from the console, guaranteeing that nothing is left over in cin, then pass the string into a stringstream to format and extract the data. If the data isn't well- formatted, when you try to extract formatted data the stream will go into failure mode and you can report an error. Similarly, if after you read data from the stringstream the stream has any remaining contents (one way to check this is to see if you can read a char out of the stringstream successfully), you can report to the user that they've entered too much. In fact, this is exactly how the CS106 library function GetInteger works! More To Explore C++ streams are extremely powerful and encompass a huge amount of functionality. While there are many more facets to explore, I highly recommending exploring some of these topics: • Random Access: Many data files store multiple pieces of information in contiguous blocks. For example, a ZIP archive containing a directory structure most likely stores each compressed file at a different offset from the start of the file. Thus, if you wanted to write a program capable of extracting a single file from the archive, you'd almost certainly need the ability to jump to arbitrary locations in a file. C++ IOStreams support this functionality with the seekg, tellg, seekp, and tellp functions (the first two for istreams, the latter for ostreams). Random access lets you quickly jump to single records in large data blocks and can be useful in data file design. • read and write: When you write numeric data to a stream, you're actually converting them into sequences of characters that represent those numbers. For example, when you print out the four- byte value 78979871, you're using eight bytes to represent the data on screen or in a file. These extra bytes can quickly add up, and it's actually possible to have on-disk representations of data that are more than twice as large as the data stored in RAM. To get around this, C++ IOStreams let you directly write data from RAM onto disk without any formatting. All ostreams support the write function that writes unformatted data to a stream, and istreams support read to read unformatted data from a stream into memory. When used well, these functions can cut file loading times and reduce disk space usage. For example, The CS106 Lexicon class uses read to quickly load its data file into memory.
  • 7. Practice Questions Don't worry, I'm not going to collect and grade these questions. However, I highly encourage you to try them out. It's one thing to see the IOStream library worked out in front of you, but it's a whole other thing to try to make it work for you! 1. Write a function ExtractFirstToken that accepts a string and returns the first token from that string. For example, if you passed in the string “Eleanor Roosevelt,” the function should return “Eleanor.” For our purposes, define a token as a single continuous block of characters with no intervening whitespace. While it's possible to write this using the C library function isspace and a for loop, there's a much shorter solution leveraging off of a stringstream. 2. Write a function HasHexLetters that accepts an int and returns whether or not that integer's hexadecimal representation contains letters. (Hint: you'll need to use the hex and dec stream manipulators in conjunction with a stringstream. Try to solve this problem without brute- forcing it: leverage off the streams library instead of using for loops.) 3. Using the code for GetInteger we covered in class and the boolalpha stream manipulator, write a function GetBoolean that waits for the user to enter “true” or “false” and returns the value.
  • 8. Quick Reference: Simplified IOStream Hierarchy ios good bad eof fail clear istream ostream iostream >> get peek read seekg tellg << put write seekp tellp ifstream ofstreamfstream open is_open ostringstreamstringstreamistringstream str open is_open open is_open strstr File Streams String Streams cin cout width fill precision