Yawn
Yawn

Reputation: 173

Casting char array into int array using atoi

Hello I'm attempting to convert a char into an int. I have a char array that was inputted through scanf, "10101" and I want to set an int array's elements equal to that char arrays elements.

example input:

10101

char aBuff[11] = {'\0'};
int aDork[5] = {0};

scanf("%s", aBuff); //aBuff is not equal to 10101, printing aBuff[0] = 1, aBuff[1] = 0 and so on

Now I want aDork[0] to equal aBuff[0] which would be 1.
Below is what I have so far.

//seems to not be working here
//I want aDork[0] to  = aBuff[0] which would be 1
//But aDork[0] is = 10101 which is the entire string of aBuff   
//aBuff is a char array that equals 10101
//aDork is an int array set with all elements set to 0

int aDork[5] = {0}
printf("aBuff[0] = %c\n", aBuff[0]); //value is 1
aDork[0] = atoi(&aBuff[0]); //why doesnt this print 1? Currently prints 10101
printf("aDork[0] = %d\n", aDork[0]); //this prints 1

printf("aBuff[1] = %c\n", aBuff[1]); //this prints 0
printf("aBuff[2] = %c\n", aBuff[2]); //this prints 1

Upvotes: 1

Views: 2575

Answers (3)

Jonathan Wood
Jonathan Wood

Reputation: 67223

Assuming aBuff contains a string of zeros and ones (that does not exceed the length of aDork), the following would transfer these values to an integer array.

for (int i = 0; i < strlen(aBuff); i++)
{
    aDork[i] = (aBuff[i] - '0');
}

Upvotes: 1

Ayman Khamouma
Ayman Khamouma

Reputation: 1006

this code is working as expected, but you are not understanding how atoi works:

Now I want aDork[0] to equal aBuff[0] which would be 1

but

aDork[0] = atoi(aBuff);

means aDork[0] will store the integer value of aBuff. Meaning the value 10101 and not the string "10101"

PS: you didn't need an array of char for aDork:

int aDork = 0;
aDork = atoi(aBuff);

is enough.

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

You ask:

aDork[0] = atoi(&aBuff[0]); // why doesnt this print 1? Currently prints 10101

It does so because:

&aBuff[0] == aBuff;

they're equivalent. The address of the first element in the array is the same address you get when referencing the array itself. So you're saying:

aDork[0] = atoi(aBuff);

which takes the whole string at aBuff and evaluates its integer value. If you want to get the value of a digit, do that:

aDork[0] = aBuff[0] - '0';   // '1' - '0' == 1, '0' - '0' == 0, etc.

and now

aDork[0] == 1;

Working example: https://ideone.com/3Vl3aI

Upvotes: 3

Related Questions