0

I had asked a question very much similar to this in the thread: https://stackoverflow.com/questions/11259474/store-the-numericals-in-char-array-into-an-integer-variable-in-vc

W.R.T. the above thread, my question is as follows:: I am working in UNICODE environment. So TCHAr would probably be treated as wchar.

My scenario is as follows:(C++)

In TCHAR a[10], the array a[] has elements (numbers) like '1','2','3' etc....

Say a[0] = '1'; a1 = '2'; a[2] = '3';

Now a[] is storing 3 characters '1', '2' and '3'. I want to store this into an int as 123 (An integer 123).

How to achieve this in C++ ?

Thanks in advance.

Community
  • 1
  • 1
codeLover
  • 3,720
  • 10
  • 65
  • 121

1 Answers1

1

First, you have to null-terminate your string. Otherwise, how do you know where to stop? Then there's a function _ttoi() specifically for that.

a[3] = 0;
int n = _ttoi[a];

You have to understand the null termination bit. Depending on how do you fill the a with characters (digits), the logic of determining the end of the string might vary.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • So if I do a[3] = '\0'; will I be able to use _ttoi() ? – codeLover Jun 29 '12 at 16:33
  • Yes. `_ttoi` expects a null terminated string. The way you show your string, it's completely unknown what is in a[3], a[4] and so forth. Depending on how you got this string (which you don't tell), it may already be null terminated. I just wanted to make sure. – Seva Alekseyev Jun 29 '12 at 16:41