0

Assume you have a character array like this.

char identity[10] = {'9','8','2','7','3','1','8','3','6','v'};

I want to grab the first two digits (in this case 9 and 8) from the character array and assign that whole value (in this case it's 98) into an integer variable.

In this case I want to put value 98 into an int variable.

If my array content is {'4','6','2','3','5','6','4','2','8','v'} then I want to set 46 as my int variable value.

How can I do this in c?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 5
    `int result = identity[0] * 10 + identity[1];` – kaylum May 26 '20 at 06:28
  • Does this answer your question? [How to convert array of integers into an integer in C?](https://stackoverflow.com/questions/19599364/how-to-convert-array-of-integers-into-an-integer-in-c) – Hulk May 26 '20 at 06:38
  • The question I proposed as duplicate tells you how to convert an entire array to an integer. To just convert the first two entries, however, it is simpler to just "unroll" the loop like @kaylum showed you. – Hulk May 26 '20 at 06:43
  • 4
    @kaylum shouldn't it be `int result = (identity[0] - '0') * 10 + (identity[1] - '0');`? – Jabberwocky May 26 '20 at 06:49
  • 1
    @Jabberwocky You are absolutely right. The OP changed the code after I posted that original comment. – kaylum May 26 '20 at 06:49
  • Yep, I also missed that edit. Now a possible dupe target might perhaps be: https://stackoverflow.com/questions/10204471/convert-char-array-to-a-int-number-in-c/10204663 (although most answers there are overkill for this situation here). – Hulk May 26 '20 at 06:50
  • @Hulk in my case i have a string array.There are not only integers in my array. Also I have a character. The way showed is fine with integer arrays. But it's not working with my case. – Kasun Jalitha May 26 '20 at 06:52
  • @KasunJalitha read my first comment – Jabberwocky May 26 '20 at 06:52
  • @kaylum Yep. I just edited it. Because i forgot to use colon sign for characters in my array. Sorry about that and Thank you. – Kasun Jalitha May 26 '20 at 06:55

1 Answers1

-2

char identity[10] = { '9','8','2','7','3','1','8','3','6','v' };

int x = identity[0] - '0';
int y = identity[1] - '0';

use ascii values