January 2007 Archives
2007-01-22
Bjarne Stroustrup's C++ Style and Technique FAQ
2007-01-21
Geeks und der Rest der Welt
2007-01-10
iostream trap
Look at this program
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "intput 1" << endl;
int i;
cin >> i;
cout << "input 2" << endl;
string foo;
getline(cin, foo);
return 0;
}
A sample run of this program is:
input 1 1 input 2It feels like the getline command is not executed. If you print the foo string afterwards it is empty. What is going on?
The reason for this is that cin >> i reads an integer
from the input stream. This integer is delimited by the newline which gets into
the input stream as the user hits return - and stays there. The subsequent
getline then reads from the input stream until the first newline which in this
case is the one before. So getline does nothing but consuming the newline.
One can fix this situation by calling getline twice. A better possibility is to
tell the istream library to discard everything until the next newline. This can
be done like this:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
I will not start to bash C++ iostreams now. I think just the facts is enough here. Thanks to Roker and netlest on #c++
2007-01-07
Friedrich Nietzsche
"Viele sind hartnäckig in bezug auf den einmal eingeschlagnen Weg, wenige in bezug auf das Ziel."Friedrich Nietzsche
2007-01-07
Spaß mit der deutschen Bahn
2007-01-04
C++ Misunderstandings
The gcc documentation has an extra section called "C++ Misunderstandings" telling the people who is to be blamed for the most common annoyances and surprises :-)
The items are
- static member declarations are not definitions
- name lookup, templates and accessing members of base classes
- temporaries may vanish before you expect
- copy assignment operators copy virtual bases twice