-6

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.

15
  • Don't use atoi, it's broken. Use std::stoi. Commented Jan 6, 2018 at 8:43
  • What should be the value of N[0]? Commented Jan 6, 2018 at 8:44
  • 1
    Why shouldn't I use atoi()? Commented Jan 6, 2018 at 8:48
  • How can -3 be a member of the char array? -3 is 2 characters! Commented Jan 6, 2018 at 8:49
  • @XcoderX why not? Commented Jan 6, 2018 at 8:54

1 Answer 1

0

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;
}

Output of the code

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.