I have a char array s[n]={1-3 2 5 6} and I want to convert it in Int array N[n] in c++ such that N[1] holds the value 1 and N[2] hold the value -3 and so on.
I have tried the function atoi but it passes all the value of array into single Int. Please help me.
1 Answer
I am using the simple approach of type casting from character to integer as, N[i] = (int)s[i] -'0';
Here N is integer array , s is the character array .I simply type cast the character array into integer , it will treat it as a ASCII code of s[i]. so I minus the '0' character (this show the number must be in original value not in ascii code).
You can try the below code! Also I am attaching the screenshot of the output of code.
#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
//character array 's' with length of 5
char s[5] = { '1', '3', '2', '5', '6' };
//before converting , prints the character array
cout << "\t\tCharacter Array" <<endl;
for (int i = 0; i < 5; i++)
{
cout << s[i] << "\t";
}
//integer array 'N' with length of 5
int N[5];
cout << "\n\tConverting Character Array to Integer Array" << endl;
//convert the character array into integer type and assigning the value into integer array 'N'
for (int i = 0; i < 5; i++)
{
N[i] = (int)s[i] - '0';
}
cout << "\t\tInteger Array" << endl;
//after converting , prints the integer array
for (int i = 0; i < 5; i++)
{
cout <<N[i]<<"\t";
}
_getch();
return 0;
}
1 Comment
sunidhi chaudhary
But this method doesn't work in case of negative numbers for example if I have -3 4 -5 in my character array then it is showing the wrong answer.

atoi, it's broken. Usestd::stoi.