TobiasKnudsen TobiasKnudsen - 8 days ago 6
C Question

Convert string to integer recursive - c programming

I'm trying to convert a string containing a number. The number is thousand separated with a dot. I've made a simple solution with

sscanf(input, "%i.%i", &first, %second); return first * 1000 + second;


This works alright, but it has its limitations as it only works for numbers below 1.000.000. I've tried making this recursive, but my program wont compile. Maybe one of you guys, can see whats wrong.

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

char* concat(const char *s1, const char *s2) {
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
strcpy(result, s1);
strcat(result, s2);
return result;
}

char *convert_spectators( char *input) //
{
char fir[3], sec[100];
int scan_res = sscanf(input, "%3[0123456789]%*[^0123456789]%s", fir, sec);

if (scan_res == 2) {
return concat(fir, convert_spectators(sec));
} else if (scan_res == 1) {
return fir;
}

}

int main() {
printf("Result: %i\n", atoi(convert_spectators("123.456.789")));
return 1;
}

Answer

from convert_spectators() you are returning "fir", which is a local array. It is wrong. I modified your code and passing fir and sec from calling function.

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

char* concat(const char *s1, const char *s2) {
    char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

char *convert_spectators( char *input, char *fir, char *sec)                                 //
{
    int scan_res = sscanf(input, "%3[0123456789]%*[^0123456789]%s", fir, sec);

    if (scan_res == 2) {
    char firTemp[4]   = "";
    char secTemp[100] = "";
        return concat(fir, convert_spectators(sec, firTemp, secTemp));
    } else if (scan_res == 1) {
        return fir;
    } else {
        printf("Something wrong, scan_res[%d]\n", scan_res);
        return NULL;
    }

}

int main() {
    char fir[4]   = "";
    char sec[100] = "";

    printf("Result: %i\n", atoi(convert_spectators("123.456.789", fir, sec)));
    return 1;
}