Article View: comp.std.c++
Article #2427a gotcha in getline(istream,string) -- why...?
From: Alex Martelli
Date: Sun, 05 Nov 1995 02:09
Date: Sun, 05 Nov 1995 02:09
47 lines
2492 bytes
2492 bytes
Trying to explain to a newbie how to do input by whole lines in C++,
the way they easily used to do it with fgets in bad ol' C, I got bit
(besides a bug in the libg++ implementation of getline(), which just
points to some obscurity between the standard libraries' usages of
length/size/capacity for strings -- obscurity enough to confuse the
implementor) by a gotcha in the standard itself:
per paragraph 21.1.1.10.8, "Inserters and extractors", getline()...:
If the function appends no characters, it calls
is.setstate(failbit), which may throw ios_base::failure
Eep. So, instead of a smooth, simple and elegant style like...:
while(getline(cin,mystr)) {
// process mystr
}
one has to adopt a convoluted...:
while(1) {
getline(cin,mystr);
if(cin.eof() || cin.bad()) break;
if(cin.fail()) { // just an empty line -- darn 21.1.1.10.8!-(
cin.clear();
}
// process mystr -- at long last!
}
Why the gratuitous spec to setstate(failbit), even possibly to throw!,
for something as innocuous as an empty line (i.e., just the terminating
'\n'), which the user could so easily test themselves if it had any
special significance for them...? I found myself unable to explain
the rationale for this to the newbie -- because I can't see any
myself. Any chance for a change...? Or, what am I missing...?
Alex
--
DISCLAIMER: these are TOTALLY personal opinions and viewpoints, NOT connected
in any way with my employer, nor any other organization or individual!
Email: martelli@cadlab.it Phone: +39 (51) 597313
CAD.LAB s.p.a., v. Ronzani 7/29, Casalecchio, Italia Fax: +39 (51) 597120
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID:
<martelli.815502013@cadlab>Path:
arc1-ca.pugleaf.net!in1.uu.net!bounce-backShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!in1.uu.net!bounce-back Date: 05 Nov 95 02:09:05 GMT Approved: fjh@cs.mu.oz.au Return-Path: <daemon@migs.UCAR.EDU> Newsgroups: comp.std.c++ From: martelli@cadlab.it (Alex Martelli) Subject: a gotcha in getline(istream,string) -- why...? Message-ID: <martelli.815502013@cadlab> Organization: Cad.Lab Spa, Bologna, Italia X-Original-Date: Sat, 4 Nov 1995 16:20:13 GMT X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUBMJwc3+EDnX0m9pzZAQEuQQGAhU/ZVkEDdjOglEh0QP1FIhKXsKDwMsLc AW6jma6K/GvbFIIBaakv4U9W7eusdLU1 =zL7y