Search code examples
cstringintprogram-entry-point

C program calling a string to int function, I am unable to convert the input


I would like to convert a string to an int and calling the function from main. Where the first character is a letter declaring the base of the number and the rest of the characters in the string are the number. I am able to get the function to work separately, but when using the main function to call it will not print out the correct values.

Example of user input using binary:

b1000
b1010

result should be:

b
b
1000
1010

Here is the code:

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

int str_to_int(inputbase) {
    char num1[50];
    num1[50] = inputbase;

    char numcpy1[sizeof(num1) - 1];

    int  i, len1;
    int result1 = 0;

    //printf("String: ");
    //gets(num1);

    //Access first character for base
    printf("%c \n", num1[0]);

    //Remove first character for number1 and number 2
    if (strlen(num1) > 0) {
        strcpy(numcpy1, &(num1[1]));
    } else {
        strcpy(numcpy1, num1);
    }
    len1 = strlen(numcpy1);

    //Turn remaining string characters into an int
    for (i = 0; i < len1; i++) {
        result1 = result1 * 10 + ( numcpy1[i] - '0' );
    }

    printf("%d \n", result1);
    return result1;
} 

int main() {
    char *number1[50], *number2[50];
    int one, two;

    printf("\nAsk numbers: \n");

    gets(number1);
    gets(number2);

    one = str_to_int(number1);
    two = str_to_int(number2);

    printf("\nVerifying...\n");
    printf("%d\n", one);
    printf("%d\n", two);

    return 0;
}

Solution

  • I suppose your code cannot be compiled because some errors.

    The first one is in the line

     int str_to_int(inputbase)
    

    where inputbase are defined without type.

    If this changed to

     int str_to_int(char * inputbase)
    

    the next point for improvement is in line

     num1[50] = inputbase;
    

    assignement like that has set of errors:

    1. num1[50] means access to 51th item, but there is only 50 items indexed from 0 to 49
    2. statement num1[0] = inputbase; (as well as with any other correct index) is wrong because of difference in types: num1[0] is char, but inputbase is pointer
    3. num1 = inputbase; will be also wrong (for copying string = cannot be used in C, so consider making loop or using standard library function strncpy)

    And since this is only the beginning of problems, I suggest starting from decimal input using some standard function for conversion char* string to int (e.g. atoi, or sscanf), then after you check the program and find it correct if it is required you can avoid using standard conversion and write your own str_to_int