Yamaha32088
Yamaha32088

Reputation: 4163

Convert characters in string to integers for multiplication

I am having trouble getting this to work. What I want to do is take user input example 1 2 3 and then multiple each character by 2 so output would be 2 4 6. Eventually I will take a long string of numbers and multiply every other character in the string by 2 leaving the rest untouched.

The problem I a having now is that I think it is multiplying the ASCII value by 2 not the actual integer by 2. Below is the code I have so far I haven't added any error checking to it yet to make sure the user inputs only numbers and not more than 16 etc. I am new to programming in C and am just doing this to learn.

#include <stdio.h>


int main(void){


char numbers[17];
int i;
    printf("Please enter number\n");
    scanf("%s", &numbers);

    for(int i=0;i<strlen(numbers);i++){
        printf("%c\n",numbers[i] * 2);
    }

}

Upvotes: 1

Views: 1865

Answers (3)

squiguy
squiguy

Reputation: 33380

Try using the atoi function like this:

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

int main(void){


char numbers[17];
int i;
    printf("Please enter number\n");
    scanf("%s", numbers);

    for(i=0;i<strlen(numbers);i++){
        printf("%c\n", atoi(numbers[i]) * 2);
    }
    return 0;
}

Upvotes: 1

user93353
user93353

Reputation: 14049

2 issues in your program

1)

scanf("%s", numbers);

2)

printf("%d\n",(numbers[i] - '0') * 2);

Here is a modfied program

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

int main()
{
    char numbers[17];
    int i, len;
    printf("Please enter number\n");
    scanf("%s", numbers);

    len = strlen(numbers);

    for(int i=0;i<len;i++)
    {
        printf("%d\n",(numbers[i] - '0') * 2);
    }

}

Also, it's better to avoid scanf - http://c-faq.com/stdio/scanfprobs.html

Upvotes: 2

Mark Wilkins
Mark Wilkins

Reputation: 41252

Something like the following might be what you are after. It assumes numbers[i] contains an ASCII digit, converts it to the corresponding integer (by subtracting the ASCII value for zero), multiplies by 2 and then adds the value for ASCII zero to that result.

printf( "%c\n", ( numbers[i] - '0' ) * 2 + '0' );

That will work for characters 0 - 4. It's not clear from my reading of the OP what is desired for digits 5-9.

Upvotes: 1

Related Questions