Search code examples
arraysintegeratoi

'atoi' function is returns only 2 digit number if I enter a 3 digit character in character array


#include <iostream>
using namespace std;
int main()
{
    char myarray[3] = {'0','1','2'};
    int i = atoi(myarray);
    cout<<i<<endl;
}

This show only 12 but I want it to be 012... Is there any other function which can do this thing?


Solution

  • There's many problems with this:

    char myarray[3] = {'0','1','2'};
    

    That misses off the NULL terminator (and hence nothing will be able to ascertain where the end of the string is). An easier way to initialise from a string is simply:

    char myarray[] = "012";
    

    This will sort the length for you and also add the NULL terminator.

    You're not getting the leading zeroes because the type you're storing the converted result in has no knowledge of how long the original input data was, or how many leading zeroes it had...it's literally just a number. If you want to also print a number of leading zeroes, you can set the minimum width using iostream.width() and set which character to use to pad it using iostream.fill(), e.g.

    cout.width(3); // At least three chars
    cout.fill('0');  // Pad with zeroes
    cout << i;
    

    I'd be questioning why you need to be able to do this though; JuniorCompressor's answer seems more for what you currently want.