Lecture 5
Function from last lecture
Input fed into this function might not be an int
could be a number that doesn't fit in an int
Failure to Read Int
0 is stored into int
cin is set to know we failed to read from it
If read fails,
cin.fail()
will be trueIf
EOF
, thencin.eof()
, andcin.fail()
are both trueIf
cin
takes something that is bigger than an int, long, etc. It will fail, otherwise, will do implicit conversion
Example 1:
Read all ints from cin, and echo them one per line to stdout. Stop if EOF or a non-int is entered.
There is an implicit conversion from cin to bool:
>>
>>
C's right bit shift operator
The operator
>>
withcin
as the first operand, C++ will call the "get from" version of operator>>
.
Rewrite Example 1:
Example:
Read ints from input until we reach EOF. Ignore any non-integers.
Example
Print hexadecimal representation of 95.
Strings
In C: an array of chars char* or char[]
Terminated with '\0'
Explicit memory management
bad if null terminator was forgotten
In C++: #include <string> type std::string
manage their own memory
string takes care of termination
easier to manipulate
Initialization
"hello" is still a string literal
still a C-style string
s is initialized from the literal string and maintains its characters
String Operations
Example
Reading with whitespace: getline(cin, s)
getline(cin, s)
Reads entire line until a newline character
Other delimiters possible
File Access
Last updated
Was this helpful?