Note:
atou() is a simplified version of
atoi().
We will use atou()
for the Index_program in Chapter_5, Sec. 5.11.
See also utoa
in Chapter_3, Sec. 3.6.
#include <stdio.h> // for printf(), scanf()
#define LENGTH 20 // max length of string
unsigned atou(char s[]); // string to unsigned integer (decimal)
int main()
{
char s[LENGTH];
printf("Enter an unsigned decimal number [+]?[0-9]+\n");
scanf("%s", s);
printf("atou(%s): %u\n", s, atou(s));
return 0;
}
unsigned atou(char s[]) // string to unsigned integer (decimal)
{
if (s[0] == '\0') // empty string
{ // not a valid decimal
printf("\"%s\" is not a valid number\n", s);
return 0; // should handle the error with an exception as we cannot
} // signal the error here with a returned value
// here s[] is not empty
int i = 0, n = 0;
if (s[i] == '+')
{
i++; // skip optional sign
}
if (s[i] == '\0' || s[i] == '-' && s[i+1] == '\0')
{
printf("\"%s\" is not a valid number\n", s);
return 0;
}
if (s[i] == '-' && s[i+1] == '0' && s[i+2] == '\0')
{return 0;}
while (s[i] != '\0')
{
if (s[i] >= '0' && s[i] <= '9')
{n = n*10 + (s[i] - '0');}
else // not a valid decimal
{
printf("\"%s\" is not a valid unsigned decimal number\n", s);
return n;
}
i++;
}
return n;
}
/*
gcc atou.c -o atou
./atou
Enter an unsigned decimal number [+]?[0-9]+
0
atou(0): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
-0
atou(-0): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
-0.0
"-0.0" is not a valid unsigned decimal number
atou(-0.0): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
-1
"-1" is not a valid unsigned decimal number
atou(-1): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
+0
atou(+0): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
+2
atou(+2): 2
./atou
Enter an unsigned decimal number [+]?[0-9]+
a
"a" is not a valid unsigned decimal number
atou(a): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
+
"+" is not a valid number
atou(+): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
-
"-" is not a valid number
atou(-): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
1.2
"1.2" is not a valid unsigned decimal number
atou(1.2): 1
./atou
Enter an unsigned decimal number [+]?[0-9]+
-1.2
"-1.2" is not a valid unsigned decimal number
atou(-1.2): 0
./atou
Enter an unsigned decimal number [+]?[0-9]+
65535 // USHRT_MAX (limits.h)
atou(65535): 65535
./atou
Enter an unsigned decimal number [+]?[0-9]+
4294967295 // UINT_MAX
atou(4294967295): 4294967295
./atou
Enter an unsigned decimal number [+]?[0-9]+
4294967296 // UINT_MAX+1
atou(4294967296): 0 // modulo 2 arithmetic
./atou
Enter an unsigned decimal number [+]?[0-9]+
4294967297 // UINT_MAX+2
atou(4294967297): 1 // modulo 2 arithmetic
*/
Note:
Compared to the previous program
(atoi),
the regular_expression
[+]?[0-9]+
is a bit simpler. [+]?
is the optional sign for an unsigned integer, which must be followed by at least one digit.
We do not allow for negative numbers, except for
-0.
Comments
Post a Comment