Re: what should atoi() do with garbage input?

From: Simon Biber (news_at_ralminNOSPAM.cc)
Date: 11/10/03


Date: Tue, 11 Nov 2003 07:48:46 +1100


"Steve Gallagher" <jeng_steveg@hotmail.com> wrote:
> Can someone tell me (hopefully with a pointer to the
> appropriate place in the Standard), what atoi() ought
> to do with the following:
>
>
> int outp = 0;
>
> outp = atoi("2+*&^%$#@!");
>
>
> One school of thought on my team is that atoi() is
> supposed to "grab the '2', convert it to 2, and basically
> just toss all that '+*&^%$#@!' stuff." Another school of
> thought is that atoi() should fail because the entire
> input was not convertiable to an int. Thanks in advance
> for any assistance.

C99 7.20.1.2#2
  Except for the behavior on error, they are equivalent
  to
    atoi: (int)strtol(nptr, (char **)NULL, 10)

C99 7.20.1.4#2
  First, they decompose the input string into three
  parts: an initial, possibly empty, sequence of
  white-space characters (as specified by the isspace
  function), a subject sequence resembling an integer
  represented in some radix determined by the value of
  base, and a final string of one or more unrecognized
  characters, including the terminating null character of
  the input string. Then, they attempt to convert the
  subject sequence to an integer, and return the result.

So, it should separate the input string "2+*&^%$#@!" into:
  initial: ""
  subject: "2"
  final: "+*&^%$#@!"
It should convert the subject, and ignore the rest of the
string.

-- 
Simon.


Relevant Pages

  • Re: sh?tpile of errors
    ... Am I going to have to use atoi ... He might well have to use it if the characters are ... there as part of a command line integer parameter. ... *isalpha* won't like argv as an argument. ...
    (comp.lang.c)
  • Re: String to Octal
    ... will store the octal number 777. ... But it atoi does this as an interger, ... The input string is "309" ... read as hex, *endp='$', ...
    (comp.lang.c)
  • Re: atoi
    ... > Im trying to convert a couple of cstring varaible to int using atoi. ... > error message if a variable contains characters. ...
    (microsoft.public.vc.mfc)