Im trying to make a program that works like atoi, you enter a number in a string, and it convert the ascii value to an int, for that I make a while loop to take the dimension of the number, but whenever I try to use a for loop next to that while program output is nothing, doesnt matter what that for is
If I delete the for loop the program works fine, why does that happen?
Here's the code
#include <stdio.h>
#include <stdlib.h>
int main() {
int cont = 0, a, array[10];
char *string;
printf("Insert a number: ");
scanf("%s", string);
while (string[cont] != 0) {
printf("%d\t", string[cont] - 48);
array[cont] = string[cont] - 48;
cont ;
}
for (int i = 0; i < 3; i ) {
printf("bruh\n");
}
}
I'm trying to multiply the value of array[i] x 10 X times and then add it, I thought I'd do a for to go through the number of numbers the array has and multiply it by 10 X times in a while loop
CodePudding user response:
string
does not point to valid memory. As such, trying to scan into it with scanf
puts you in the realm of undefined behavior.
You need to either automatically or dynamically allocate memory for that character array. Something like:
char string[1024];
scanf("23s", string);
Using the 23s
specifier indicates a maximum width so that a buffer overflow does not occur. You should also check that scanf
returns 1
to indicate that one value was successfully read.
CodePudding user response:
You need to have a value
to accumulate the sum of the digits. Was it a
?
Also here
int cont = 0, a, array[10];
char *string;
you forgot to make string
point to array
as in
char array[10];
char *string = array;
so your pointer is not valid. And string
should be char[10]
Another consideration is the signal. The array size is ok since INT_MAX
is 2147483647
and has 10 digits, so it is safe to use 9
and the final NULL
in the input string with no overflow or underflow POSSIBLE: from -999,999,999 to 999,999,999 ALL VALUES fits in an int
.
Note that scanf()
is buffered anyway until reading the '\n'
so you are doing two loops: one until '\n'
inside 'scanf'
and another until '0'
in the while
. And you still have the problem of filtering the digits from the string.
See this alternative:
#include <stdio.h>
int main(void)
{
int n_dig = 0;
int sig = 1;
int value = 0;
// may have a signal
printf("Insert a number (optional sign up to 9 digits): ");
int ch = fgetc(stdin);
if (ch == '-')
sig = -1;
else if (ch == ' ')
sig = 1;
else if (ch < '0')
return 0;
else if (ch > '9')
return 0;
else
n_dig = 1, value = ch - '0';
// '\n' ends all
while ((ch = fgetc(stdin)) != '\n')
{
if (ch < '0' || ch > '9') break;
value = (10 * value) (ch - '0');
n_dig = 1;
if (n_dig == 9) break;
};
if (n_dig == 0) return -1;
printf("Decimal value is %d\n", sig * value);
return 0;
}
Differences
- a single loop using fgetc()
- a signal is ok,
-
- input of only a signal returns error
- any non-digit exits the loop
- goes up to 9 digits and a signal