R. Clayton (rclayton@clayton.cs.monmouth.edu)
(no date)
I've written the following procedure to test if a string contains an integer:
bool is_int(string s) {
istringstream ss(s);
int i;
if (! ss >> i)
return false;
else
return true;
}
Shouldn't (ss >> i) return 'false', as it could not convert the whole string
into an integer?
No, because stream extraction doesn't have to read the whole string (or input
stream), it just reads the part that matches the format of the value its
trying to read (int in this case).
I found that it converts "7c" into the integer 7, ignores the "c" and
returns true. Is this correct behaviour?
Yes, although I haven't found a description of how stream extraction works
for integers.
Should I check ss again to see any leftover characters?
Yes, but you have to do even more work than that, because some characters -
space characters, for example - may legitimately follow an integer; "7 " for
example.
However, I recommend you think of another approach. The first problem with
is_int() as you have it above is that it's not a simple matter to get it
working correctly. In addition to the problems above, the if guard
! ss >> i
is wrong, because it's parenthesized as
(!ss) >> i
(! has higher precedence than does >>). This guard actually does no input at
all because (!ss) is turned into an integer and >> is interpreted as a right
shift operator because it's got integers on both sides. Even better, (!ss)
is always 0 (because a stream can't indicate eof until it's been read, and ss
has never been read at the time it's tested), so the guard is always false,
and is_int() always returns true.
Even if you get is_int() working correctly, it's still an expensive way to
test for an integer. If you want some help thinking of a better way to check
for an integer, you might want to look at Section 19.7, Finding Characters in
a string, from Deitel and Deitel.
This archive was generated by hypermail 2.0b3 on Fri May 10 2002 - 12:45:04 EDT