user2877858 user2877858 - 23 days ago 5
C Question

My program doesn't manipulate a string's values correctly

I need to code a program that gets input values for a string, then it ignores the characters that are not digits and it uses the digits from the string to create an integer and display it. here are some strings turned into integers as stated in the exercise.

I wanted to go through the string as through a vector, then test if the each position is a digit using isdigit(s[i]), then put these values in another vector which creates a number using the digits. At the end it's supposed to output the number. I can't for the life of it figure what's wrong, please help.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char *s;
scanf("%s", s);
printf("%s\n", s);

int i, n=0, v[100], nr=0;
for(i=0; i<strlen(s); i++)
{
if (isdigit(s[i]) == 1)
{
v[i] = s[i];
n++;
}
}
for(i=0;i<n;i++)
{
printf("%c\n", v[i]);
}

for(i=0; i<n; i++)
{
nr = nr * 10;
nr = nr + v[i];
}
printf("%d", nr);
return 0;
}

usr usr
Answer

The pointer s is unintialized which is your major problem. But there are other problems too.

  • isdigit() is documented to return a non-zero return code which is not necessarily 1.

  • The argument to isdigit() needs to be cast to unsigned char to avoid potential undefined behaviour.

  • Your array v is also using the same index variable i - which is not right. Use a different variable to index v when you store the digits.

  • You need to subtract '0' to get the each digits integer equivalent.

  • scanf()'s format %s can't handle inputs with space (among other problems). So, use fgets().


#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
char s[256];
fgets(s, sizeof s, stdin);
s[strcspn(s, "\n")] = 0; /* remove trailing newline if present */
printf("%s\n", s);

int i, n = 0, v[100], nr = 0;
size_t j = 0;
for(i = 0; i < s[i]; i++)
{
    if (isdigit((unsigned char)s[i]))
    {
        v[j++] = s[i];
        n++;
    }
}
for(i = 0;i < j; i++)
{
    printf("%c\n", v[i]);
}

if (j) { /* No digit was seen */
    int multiply = 1;
    for(i= j-1 ; i >= 0; i--) {
        nr = nr + (v[i] - '0') * multiply;
        multiply *= 10;
    }
}

printf("%d", nr);
return 0;
}

In addition be aware of integer overflow of nr (and/or multiply) can't hold if your input contains too many digits.

Another potential source of issue is that if you input over 100 digits then it'll overflow the array v, leading to undefined behaviour.