Jump to content

Conversion from char array to int array.

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
6 replies to this topic

#1
TheUmer

TheUmer

    Newbie

  • Members
  • PipPip
  • 27 posts
I'm using the following code to do so:

#include <stdio.h>

int main ()
{
int i;
char ch[20]="1 2 34 4 56672332432";
int ch1[20];
for (i=0; i<20; i++)
{
      ch1[i]=(int)ch[i]-'0';
}
for (i=0; i<20; i++)
{
      printf ("%d\n ", ch1[i]);
}
return 0;
}

The problem is I can't an integer more than 9 as it is. For example, the array is reading and converting each char separately, so for example if I want to get 34 form char array into an integer 34, it won't do so. It picks and gives 3 separately and 4 separately.

What should I do for this problem?

#2
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
example
char myarray[] = "1,2,3,4,5"
int array[5]
for(int i=0; i<5; i++)
{
array[i] = stoi(myarray[i]);
}

#3
TheUmer

TheUmer

    Newbie

  • Members
  • PipPip
  • 27 posts
#include <stdlib.h> this would be used for using stoi, right? But compiler is giving an error: "undefined reference to stoi"

What to be done?

#4
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
I'm sorry its atoi

fix it xD

#5
TheUmer

TheUmer

    Newbie

  • Members
  • PipPip
  • 27 posts
Fine. But when used atoi instread of stoi, it gives the following error:

"passing argument 1 of ‘atoi’ makes pointer from integer without a cast."

What now? :s

#6
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
Uhm, sorry i can't get it to work :/

#7
fread

fread

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 787 posts
I think you should rethink your strategy. A char array will count that whitespace as a valid char and any manipulation you make on the items in the array will be done on the whitespace char. Dont forget a char is a single character. I think things like 34 would be counted as two chars since each char occupies one position in the array and 34 would occupy two.
Perfection of means and confusion of ends seem to characterize our age. Albert Einstein :confused: