On 10 May 2004 20:18:25 GMT, Alex Neumann <nospam@web.de> wrote:
[color=blue]
>Hi,
>
>I need a function which converts an string to an integer.
>Currently I have this:
>
>bool string2int(char* digit, int& result)
>{
> result = 0;
>
> if (!(*digit >= '0' && *digit <='9'))
> return false;
> while (*digit >= '0' && *digit <='9')
> {
> result = (result * 10) + (*digit - '0');
> digit++;
> }
>
> if (*digit != 0 && *digit != ',' && *digit != ']')
> {
> return false;
> }
>
>return true;
>}
>
>Has someone a better idea ?
>Only ISO C++ please, no extra libs ;-)[/color]
Well, you're doing things the hard way and not being as flexible as
facilities you already have in your libraries. If you want to code it by
hand, you could be using <cctype> facilities (e.g. isdigit), checking for
leading white space, etc. Note that C libs are also ISO C++, so my
suggestion to you would be to let the libs do all the heavy lifting:
#include <cstdio>
bool string2int(const char *intext, int &result)
{
return std::sscanf(intext, "%d", &result);
}
-leor
--
Leor Zolman --- BD Software ---
www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html