CIS 190: C/C++ Programming
Lecture 7
C++ Streams
Outline
Handling Streams in C++
Input Control
Output Control
String Streams
Errors in C++
Header Protection
Homework
Using Input Streams
input streams include
istream
like reading in from the terminal
ifstream
like reading in from a file
istringstream
which well cover later today
3
Using Input Streams
there are many ways to use input streams,
with varying levels of precision/control
the >> operator
read()
ignore()
get()
getline()
Types of Whitespace
many of the input streams delineate using
whitespace
theyll skip leading whitespace
and stop at the next whitespace
common types of whitespace:
space, tab, newline
carriage return (\r) can cause problems
sometimes used in Windows and Mac files
5
The >> Operator
returns a boolean for (un)successful read
just like scanf and fscanf:
skips leading whitespace
stops at the next whitespace
(without reading it in)
appends a null terminator to strings read in
The >> Operator: Example
cout << Please enter your first
<< and last name separated
<< by a space: ;
cin >> firstName >> lastName;
cout << Please enter your age:
cin >> age;
ignore()
istream& ignore (streamsize n = 1,
int delim
= EOF);
takes in:
an integer
a character delimiter
(default value: 1)
(default value: EOF)
both arguments are optional
8
ignore()
istream& ignore (streamsize n = 1,
int delim
= EOF);
ignore extracts characters and discards them
until either:
n characters are extracted
delim is reached
ignore(): Example
istream& ignore (streamsize n = 1,
int delim
= EOF);
[Link]();
[Link]( );
[Link](512);
[Link](512, );
10
read()
istream& read (char* s,
streamsize n);
takes in:
a character array (a C string)
a size
streamsize is a typedef of a
signed integral type
11
read()
istream& read (char* s,
streamsize n);
copies a block of data of size n characters
stops after n characters, or at EOF
without checking its contents
without appending a NULL terminator
without moving through the input
often used in conjuction with ignore()
12
read(): Example
istream& read (char* s,
streamsize n);
char strArr[SIZE];
[Link](strArr, SIZE-1);
/* do stuff with strArr */
// if you want to move on:
[Link](SIZE-1);
13
get()
istream& get (char &c);
takes in
a pointer to a character
stores a single character
does not skip whitespace
[Link](&character);
14
get()
int
get ();
returns a single character
the ASCII value of the character read in
character = [Link]();
15
Multiple Prototypes
get() has two prototypes:
int
get ();
istream& get (char &c);
this is called overloading
many library functions are overloaded
which function is called depends on the arguments
you too can do this in C++ (well cover it soon)
16
getline()
istream& getline (char* s,
streamsize n);
takes in:
a character array
a size
extracts up to n characters
stops extracting characters upon hitting \n
also stops if it hits EOF
17
getline()
istream& getline (char* s,
streamsize n);
the newline is read in, and discarded
(not stored in the character array)
carriage returns can cause problems, so be
aware of the files origin and format
18
getline(): Example
istream& getline (char* s,
streamsize n);
char chArray [128];
[Link](chArray, 128-1);
/* use 128-1 to leave room
for the null terminator */
19
istream& ?
istream& ignore (streamsize n = 1,
int delim
= EOF);
istream& read (char* s,
streamsize n);
istream& get (char &c);
istream& getline (char* s,
streamsize n);
20
istream& ?
istream& ignore (streamsize n = 1,
int delim
= EOF);
istream& read (char* s,
streamsize n);
istream& get (char &c);
istream& getline (char* s,
streamsize n);
all of these functions return a reference to an
object of type istream
21
istream&
istream is the class type that all other input
stream types are derived from
like cin and input files
the function is returning a reference to an
object of type istream
references are kind of like pointers
well cover this in more detail later
22
More Ways to Handle Input
[Link]/reference/istream/istream/
peek()
putback()
unget()
gcount()
tellg()
can be very useful, but make sure you know
exactly what its doing before you use it
23
Outline
Handling Streams in C++
Input Control
Output Control
String Streams
Errors in C++
Header Protection
Homework
24
Using Output Streams
output streams include
ostream
like printing out to the terminal
ofstream
like writing to a file
ostringstream
which well cover later today
25
The <iomanip> Library
used to format output in C++
can be used on any output stream
ostream
ofstream
ostringstream
must have #include <iomanip>
IO Manipulation
iomanip replaces the formatting we did
inside the printf() statements:
printf(itll %-6s for %07.3f hours\n,
rain, 3.14159);
> itll rain
for 003.142 hours
iomanip isnt as compact as printf(),
but its cleaner, and the code is clearer
27
The <iomanip> Library Functions
setw()
used to set width of field
setfill()
used to set a fill character (0 or or _, etc.)
setprecision()
used to set decimal precision
left and right
used to set alignment (not actually iomanip)
28
Sticky
most of the parametric manipulators are
sticky once they are set, those
manipulations apply to all future parameters
unless changed by another call
setfill(), setprecision(), and left/right
others only apply to the directly following
output, and must be re-called each parameter
setw()
29
setw()
set the width of the next output
NOT sticky
cout << Hello << setw(10)
<< world << . << endl;
Hello
world.
will not cut off the output: input given is
minimum amount of characters to be printed
30
setfill()
change padding character
(space) is default padding character
cout << setfill(-) << setw(8)
<< hey << endl;
-----hey
padding character is set until changed again
IS sticky
31
setprecision()
change maximum number of digits to display
numbers in total, not before or after decimal
cout << setprecision(5)
<< 3.1415926535 << endl;
3.1416
precision holds for all future numbers
IS sticky
32
setprecision()
not affected by calls to setfill()
attempts to round, but its not always perfect
ints behave best, then doubles; floats are worst
an example:
temp = 12.3456789 and test = 1234567.89
cout << temp << and << test << endl;
12.3457 and 1.23457e+06
33
setprecision(): Example
set precision: 1
1e+01 and 1e+06
set precision: 2
12 and 1.2e+06
set precision: 3
12.3 and 1.23e+06
set precision: 9
12.3456789 and 1234567.89
34
setprecision(): Example
set precision: 1
1e+01 and 1e+06
set precision: 2
12 and 1.2e+06
set precision: 3
12.3 and 1.23e+06
set precision: 9
12.3456789 and 1234567.89
set precision: 20
12.345678899999999345 and
1234567.8899999998976
35
Alignment
in printf(), we used a negative to left align,
since right align was always used by default
when using ostream, right is still default
instead we use keywords left and right
note that there are no parentheses
(they are not functions)
IS sticky
36
Alignment: Example
cout << setw(8) << hello << endl;
cout << setw(8) << left << cruel
<< endl;
cout << setw(8) << right << world
<< endl;
hello
cruel
world
37
Livecoding iomanip Examples
well be using iomanip to:
left and right align
adjust width
change precision
set fill characters
LIVECODING
38
Outline
Handling Streams in C++
Input Control
Output Control
String Streams
Errors in C++
Header Protection
Homework
39
String Streams
allow us to use stream functions on strings
must have #include <sstream>
helpful for formatting strings
two types
ostringstream
istringstream
40
Using String Streams
istringstream is an input stream, so we
can use any of the functions for input
manipulation
read(), >>, ignore(), etc.
ostringstream is an output stream, so
we can use any of the iomanip tools
setw(), setfill(), left, etc.
41
Common Uses for String Streams
use istringstream for
parsing a given string
use ostringstream for
creating a new string with specific formatting
42
The str() Function
two different prototypes for str()
string str () const;
void
str (const string& s);
another overloaded function
which version the program calls is
determined by the arguments you pass in
43
Two Forms of str()
string str () const;
converts from a string stream to a string
void
str (const string& s);
converts from a string to a string stream
44
Using First Form of str()
string str () const;
returns a string containing a copy of the
current contents of the stream
converts from a string stream to a string
newStr = [Link]();
45
Using Second Form of str()
void
str (const string& s);
wipes contents of string stream, and sets to
the contents of the passed-in string
converts from a string to a string stream
[Link](oldStr);
[Link](hello);
46
Outline
Handling Streams in C++
Input Control
Output Control
String Streams
Errors in C++
Header Protection
Homework
47
Errors in C++
are often MUCH longer than similar errors in C
makes it even more important to start with
the very first error, all the way at the top
basic errors (typos, missing semicolons, etc.)
remain largely the same
48
???
49
???
[Link]: In function 'int main()':
[Link]:10: error: no match for 'operator<<' in
'std::cin << fileName'
[Link]:10: note: candidates are:
In file included from /usr/include/c++/4.7/string:54:0,
from
/usr/include/c++/4.7/bits/locale_classes.h:42,
from /usr/include/c++/4.7/bits/ios_base.h:43,
from /usr/include/c++/4.7/ios:43,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/basic_string.h:2750:5: not
[]
50
???
[Link]: In function 'int main()':
[Link]:10: error: no match for 'operator<<' in
'std::cin << fileName'
[Link]:10: note: candidates are:
In file included from /usr/include/c++/4.7/string:54:0,
from
/usr/include/c++/4.7/bits/locale_classes.h:42,
from /usr/include/c++/4.7/bits/ios_base.h:43,
from /usr/include/c++/4.7/ios:43,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/basic_string.h:2750:5: not
[]
51
Used << instead of >>
[Link]: In function 'int main()':
[Link]:10: error: no match for 'operator<<' in
'std::cin << fileName'
[Link]:10: note: candidates are:
In file included from /usr/include/c++/4.7/string:54:0,
from
/usr/include/c++/4.7/bits/locale_classes.h:42,
from /usr/include/c++/4.7/bits/ios_base.h:43,
from /usr/include/c++/4.7/ios:43,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/basic_string.h:2750:5: not
[]
52
???
[Link]: In function 'int main()':
[Link]:3: error: 'string' was not declared in
this scope
[Link]:3: note: suggested alternative:
In file included from
/usr/include/c++/4.7/iosfw[Link],
from /usr/include/c++/4.7/ios:39,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/stringfwd.h:65:33:
note: 'std::string
[]
53
???
[Link]: In function 'int main()':
[Link]:3: error: 'string' was not declared in
this scope
[Link]:3: note: suggested alternative:
In file included from
/usr/include/c++/4.7/iosfw[Link],
from /usr/include/c++/4.7/ios:39,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/stringfwd.h:65:33:
note: 'std::string
[]
54
???
[Link]: In function 'int main()':
[Link]:3: error: 'string' was not declared in
this scope
[Link]:3: note: suggested alternative:
In file included from
/usr/include/c++/4.7/iosfw[Link],
from /usr/include/c++/4.7/ios:39,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/stringfwd.h:65:33:
note: 'std::string
[]
55
Forgot using namespace std;
[Link]: In function 'int main()':
[Link]:3: error: 'string' was not declared in
this scope
[Link]:3: note: suggested alternative:
In file included from
/usr/include/c++/4.7/iosfw[Link],
from /usr/include/c++/4.7/ios:39,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from [Link]:
/usr/include/c++/4.7/bits/stringfwd.h:65:33:
note: 'std::string
[]
56
???
[Link]: In function 'int main()':
[Link]:12: error: aggregate
'std::ifstream inStream' has incomplete type
and cannot be defined
[Link]:12: error: aggregate
'std::ofstream jpegFile' has incomplete type
and cannot be defined
make: *** [recover] Error 1
57
???
[Link]: In function 'int main()':
[Link]:12: error: aggregate
'std::ifstream inStream' has incomplete type
and cannot be defined
[Link]:12: error: aggregate
'std::ofstream jpegFile' has incomplete type
and cannot be defined
make: *** [recover] Error 1
58
???
[Link]: In function 'int main()':
[Link]:12: error: aggregate
'std::ifstream inStream' has incomplete type
and cannot be defined
[Link]:12: error: aggregate
'std::ofstream jpegFile' has incomplete type
and cannot be defined
make: *** [recover] Error 1
59
Forgot #include <fstream>
[Link]: In function 'int main()':
[Link]:12: error: aggregate
'std::ifstream inStream' has incomplete type
and cannot be defined
[Link]:12: error: aggregate
'std::ofstream jpegFile' has incomplete type
and cannot be defined
make: *** [recover] Error 1
60
???
[Link]: In function 'int main()':
[Link]:12: error: 'exit' was not declared
in this scope
[Link]:9: error: 'exit' was not declared
in this scope
make: *** [recover] Error 1
61
???
[Link]: In function 'int main()':
[Link]:12: error: 'exit' was not declared
in this scope
[Link]:9: error: 'exit' was not declared
in this scope
make: *** [recover] Error 1
62
Forget #include <cstdlib>
[Link]: In function 'int main()':
[Link]:12: error: 'exit' was not declared
in this scope
[Link]:9: error: 'exit' was not declared
in this scope
make: *** [recover] Error 1
63
Outline
Handling Streams in C++
Input Control
Output Control
String Streams
Errors in C++
Header Protection
Homework
64
Headers in C++
handled the same way as in C
including user .h files:
#include userFile.h
including C++ libraries
#include <iostream>
65
An Example
typedef struct bar{
int a;
} BAR;
bar.h
#include bar.h
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include bar.h
#include foo.h
int main()
{
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
66
An Example
typedef struct bar{
int a;
} BAR;
bar.h
#include bar.h
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include bar.h
#include foo.h
int main()
{
BAR i;
FOO j;
when we try
to compile
this
/* ... */
return 0;
}
main.c
67
An Example
typedef struct bar{
int a;
} BAR;
#include bar.h
#include foo.h
when we try
to compile
this
int main()
bar.h
{
BAR i;
FOO j;
#include
bar.h from foo.h:1:0,
In
file included
from main.[Link]
/* ... */
typedef struct
foo{redefinition
bar.h:1:16:
error:
of 'struct bar'
x;included from main.[Link]
In BAR
file
return
0;
char y;
bar.h:1:16:
note: originally
defined
here
}
} FOO;
In
file included from foo.h:1:0,
from main.[Link]
foo.h
bar.h:3:3:
error: conflicting main.c
types for 'BAR'
In file included from main.[Link]
bar.h:3:3: note: previous declaration of 'BAR' was here
68
An Example
typedef struct bar{
int a;
} BAR;
#include bar.h
#include foo.h
when we try
to compile
this
int main()
bar.h
{
BAR i;
FOO j;
#include
bar.h from foo.h:1:0,
In
file included
from main.[Link]
/* ... */
typedef struct
foo{redefinition
bar.h:1:16:
error:
of 'struct bar'
x;included from main.[Link]
In BAR
file
return
0;
char y;
bar.h:1:16:
note: originally
defined
here
}
} FOO;
In
file included from foo.h:1:0,
from main.[Link]
foo.h
bar.h:3:3:
error: conflicting main.c
types for 'BAR'
In file included from main.[Link]
bar.h:3:3: note: previous declaration of 'BAR' was here
69
What the Compiler is Seeing
typedef struct bar{
int a;
} BAR;
#include bar.h
bar.h
#include foo.h
#include bar.h
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
70
What the Compiler is Seeing
typedef struct bar{
int a;
} BAR;
#include bar.h
bar.h
#include foo.h
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
71
What the Compiler is Seeing
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
bar.h
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h
#include foo.h
#include
bar.h
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
72
What the Compiler is Seeing
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
bar.h
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h typedef struct foo{
BAR x;
char y;
} FOO;
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
#include
bar.h
#include
foo.h
73
What the Compiler is Seeing
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
bar.h
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h typedef struct foo{
BAR x;
char y;
} FOO;
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
#include
bar.h
#include
foo.h
74
Header Protection
for our program to work, we need to have the
definition of the BAR struct in both:
foo.h
main.c
the easiest way to solve this problem is
through the use of header guards
75
Header Guards
in each .h file, use the following:
76
Header Guards
in each .h file, use the following:
#ifndef BAR_H if not (previously) defined
77
Header Guards
in each .h file, use the following:
#ifndef BAR_H if not (previously) defined
#define BAR_H then define
78
Header Guards
in each .h file, use the following:
#ifndef BAR_H if not (previously) defined
#define BAR_H then define
[CONTENTS OF .H FILE GO HERE]
79
Header Guards
in each .h file, use the following:
#ifndef BAR_H if not (previously) defined
#define BAR_H then define
[CONTENTS OF .H FILE GO HERE]
#endif /* BAR_H */ stop the if at this
point (end of the file)
80
A Fixed Example
#include bar.h
#include foo.h
typedef struct bar{
int a;
} BAR;
#include bar.h
typedef struct foo{
BAR x;
char y;
} FOO;
int main()
{
BAR i;
FOO j;
/* ... */
bar.h
return 0;
}
foo.h
main.c
81
A Fixed Example
#ifndef BAR_H
#define BAR_H
#ifndef FOO_H
#define FOO_H
#include bar.h
#include foo.h
typedef struct bar{
int a;
} BAR;
#include bar.h
int main()
{
BAR i;
FOO j;
#endif /*BAR_H*/
typedef struct foo{
BAR x;
char y;
} FOO;
/* ... */
bar.h
#endif /*FOO_H*/
return 0;
}
foo.h
main.c
82
What the Compiler Sees Fixed
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
bar.h
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h typedef struct foo{
BAR x;
char y;
} FOO;
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
#include
bar.h
#include
foo.h
83
What the Compiler Sees Fixed
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
bar.h
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h typedef struct foo{
BAR x;
char y;
} FOO;
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
#include
bar.h
#include
foo.h
84
What the Compiler Sees Fixed
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
bar.h
typedef struct bar{
int a;
} BAR;
typedef struct bar{
int a;
} BAR;
typedef struct foo{
BAR x;
char y;
} FOO;
foo.h
#include
bar.h typedef struct foo{
BAR x;
char y;
} FOO;
int main() {
BAR i;
FOO j;
/* ... */
return 0;
}
main.c
#include
bar.h
#include
foo.h
85
Using Header Guards
can prevent a lot of errors
still need to be mindful!!!
dont just include every possible header and
let header guards handle it for you
86
Outline
Handling Streams in C++
Input Control
Output Control
String Streams
Errors in C++
Header Protection
Homework
87
Homework 5
Murder Mystery
heavy on use of streams
not everything you need was covered in class
look at the [Link] pages on streams!
should be much easier (and shorter) than
Homework 4B
88