简体   繁体   中英

Scanning a integer from a character array

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int a[10];
    for (int i=0 ; i<10;i++){
        a[i]=0;
    }

    char *str = (char *)malloc(1024*sizeof(char));
    scanf("%s",str);
    str = realloc(str, strlen(str)+1);

    for (int i = 0;i<strlen(str);i++){

        for ( int j = 0;j<=9;j++){
            if(*str=='j') a[j]++;
        }

        str++;
    }
    for (int i=0 ; i<10;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

In this code during the if(*str=='j') a[j]++; the condition *str == j is always returning false, due to which the value of a[j] is not changing at all.

Why is this happening and what can I do to fix this?

The code is supposed to scan for integer in a given array and give the frequency of the digit occured.

Example Input : a11472o5t6

Output : 0 2 1 0 1 1 1 1 0 0

  • The str = realloc(str, strlen(str)+1); step is pointless. You could just delete this line.
  • Comparison to j is pointless. Since you are counting digits, it should be '0' + j instead.
  • Instead of advancing str with str++ I suggest str[i] . This way you still have your original str pointer around in case you want to pass it into printf or strlen for example.

For the inner loop try this instead:

for ( int j = 0; j <= 9; j++ )
{
    if(str[i] == ('0' + j)) a[j]++;
}

I think perhaps what you want is if(*str=='0'+j) a[j]++;

In other words, if j is zero, check for a '0' character; if j is 1, check for '1', and so on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM