0

So I'm a newcomer to C and I've just learned about string after array. Now I'm trying to write a program that convert a string which consists of only integer numbers into an integer array.

For example let's say I have this string og[] and use fgets to get the input: og = 123456

Then I want to convert this '012345678' string into an array, let's say mod[] which be like:

mod[0] = 1; 
mod[1] = 2;
mod[2] = 3;
mod[3] = 4;
mod[4] = 5;
mod[5] = 6;

Is there any method to achieve this quickly with a function? If no, how could I write a function to convert this?

Thank you in advance.

2 Answers 2

1

Use ASCII difference method in order to get required outcome:

For example let you are converting (char)1 to (int)1. So Subtract ASCII value of 1 by 0:

ie,'1'-'0'(since, 49-48=1 here 49 is ASCII value of '1' and 48 is of '0'). And at the end store it into integer variable.

By using above concept you code will be:

 int i=0;
char str []="123456789";
int strsize=(sizeof(str)/sizeof(char))-1;
int *arr=(int * )malloc(strsize*sizeof(int));
    // YOUR ANSWER STARTS HERE
while(str[i]!='\0'){
    arr[i]=str[i]-'0';
    i++;
}

here size of str string is 10 thus subtracting 1 from it in order to get 9. here while loop moving till end of string (i.e '\0')

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this seems to have resolved my problem. I wasn't aware of the ASCII table so this method is really new to me. It's seem that I will have to look into this soon to fully utilize it.
1

If you are using an ASCII-based system (very likely) and you are only concerned with single digits, this is quite simple:

int main(void)
{
    char og[] = "123456";
    int *mod = calloc(strlen(og),sizeof(*mod));

    for (int i = 0; og[i]; ++i) {
        mod[i] = og[i] - '0';
    }
    // then whatever you want to do with this
}

This works because in ASCII, decimal digits are sequential and when the character is '0' and you subtract '0' (which is 48 in ASCII), you get the numerical value of 0; when the character is '1' (which is 49 in ASCII), you get the numerical value 1; and so on.

1 Comment

Thank you very much, this also seems to have resolved my problem. Turning this into a function is easy so it's really convenient for the program I'm writing. It seems that I will have to look into this ASCII thing soon to be able to use it effectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.