The following code is supposed to convert a numeric string to an integer, but it does not work. I am trying to use GDB to see what is going on, but still can not follow the program. When I put in 1, the program return the right number but when I put in 12, the program returns -429. Here is the code:
Code:
#include <stdio.h>
int main ()
{
int a;
a = getint ();
printf ("You entered ...%d", a);
printf ("Press any key to continue ...");
getch();
}
getint ()
{
int val,i,j,k;
char str[6];
i = 0;
while ( i <= 5)
{
str[i] = getche();
if ( str[i] == '\r')
{
str[i]='\0';
break;
}
if ( str[i] == '\b')
{
printf ("\b");
i--;
}
else
i++;
}
val = 0;
k = 1;
for ( j = i-1; j >=0; j--)
{
val = val + ( str[j] - 48 * k);
k = k * 10;
}
return val;
}
I am also wondering what are the GDB outputs which start with $. I will try to do a more detailed search online; the GDB tutorials online do not seem to have anything about this. Below is a capture of what I mean:
Code:
(gdb) p k
$3 = 1
(gdb)
$4 = 1
(gdb)
$5 = 1
(gdb) s
33 for ( j = i-1; j >=0; j--)
(gdb) s
35 val = val + ( str[j] - 48 * k);
(gdb) p j
$6 = 4
(gdb) p val
$7 = 6
(gdb) s
36 k = k * 10;
(gdb) s
33 for ( j = i-1; j >=0; j--)
(gdb) s
35 val = val + ( str[j] - 48 * k);
(gdb) quit