-3

I'm working on a C program and i am struggling with it (I've been spoiled by the concept of object orientation).

What i want to do is this:

I want to put values in a char array into an int. So for example i have char[0] == '1' and char[1] == '2'. I want to put these values in an int variable so its value is 12. I have tried looking but I am not sure how to get this done.

I really am poor at explaining so please ask for more info if necessary.

Zachi Shtain
  • 826
  • 1
  • 13
  • 31
MrMalo
  • 1
  • 2
  • 1
    your question shows the lack of personal research. there are tons of examples out there to solve this minor common problem. – Jason Hu Aug 14 '15 at 16:53
  • possible duplicate of [How do you use atoi to assign individual elements of a char array?](http://stackoverflow.com/questions/3251401/how-do-you-use-atoi-to-assign-individual-elements-of-a-char-array) – dbush Aug 14 '15 at 16:56
  • do you know the size of your char array? – Zachi Shtain Aug 14 '15 at 16:59
  • 1
    int foo = (char_array[0] & 0x0f)*10 + (char_array[0] & 0x0f). Don't call your characters char – Oleg Mazurov Aug 14 '15 at 16:59
  • I think this will help: [atoi](http://www.cplusplus.com/reference/cstdlib/atoi/) – Milan Patel Aug 14 '15 at 17:06
  • `char buf[]={"12"}; int a = atoi(buf);` – ryyker Aug 14 '15 at 17:07
  • `int value = 0; for (int i = 0; i < lengthOfArray; ++i) { value *= 10; value += array[i]; }`. When someone can answer your question in one sentence, you have probably not given it enough thought and are doing yourself a learning disservice. – mah Aug 14 '15 at 17:08
  • thanks @OlegMazurov that actually helped. Thanks alot – MrMalo Aug 14 '15 at 17:13

3 Answers3

2

If your char array is made with characters '1' and '2':

char a[2];
a[0] = '1';
a[1] = '2';
int b = (a[0]-'0')*10 + (a[1]-'0');

If your char array is made with numbers 1 and 2:

char a[2];
a[0] = 1;
a[1] = 2;
int b = a[0] * 10 + a[1];

also, see: Why does subtracting '0' in C result in the number that the char is representing?

Community
  • 1
  • 1
orestisf
  • 1,396
  • 1
  • 15
  • 30
  • Thanks alot. This also worked.Quite a simple solution actually. Not sure how i didn't think of this. – MrMalo Aug 14 '15 at 17:15
1

If the character array contains a string that is if it is zero-terminated then you can apply standard C function atoi declared in header <stdlib.h>.

For example

char s[] = "12";
int x = atoi( s );

If the array is not zero-terminated as

char s[2] = "12";

then you can convert its content to an integer manually.

For example

int x = 0;

for ( size_t i = 0; i < sizeof( s ) / sizeof( *s ); i++ )
{
    x = 10 * x + s[i] - '0';
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

What you are trying to do is called parsing. In c this can be done with the atoi() function like this:

 char s[] = "12";
 int num = atoi(s);
Julius Naeumann
  • 422
  • 1
  • 10
  • 19