How to Convert Char* to Int & C++

Save

Converting a char to an int in c++ is a common operation when sorting a char array or storing numbers in a char array. A char is a pointer to a char data type or a string of char data types. Char data types can be any English characters (e.g. a through z) or any ASCII character. An int is a data type that can hold integers, i.e. whole numbers.

  • Place your char, we'll call it pcMyCharStar, into the condition section of an "if" statement. This verifies that your char is pointing to a char or a string of chars, and therefore does not equal nil.

    e.g.

    if( pcMyCharStar )

    {

    // Your pcMyCharStar does NOT equal to nil.

    }

    else

    {

    // Your pcMyCharStar does equal nil.

    }

  • Access the data stored in the char by placing the de-referencing operator to the left of our char . e.g. char myChar= pcMyCharStar;

    This operation gives access to the data the pointer was referencing. Another way to do this is by treating the char* as an array and using the "[ ]" operator.

    e.g. char myChar= pcMyCharStar[0];

    This operator returns the first element or the only element in the char* array.

  • Typecast the data accessed in step two into an int by placing the data type you are casting to in between parenthesis to the left of the variable you are casting. e.g.

    int nMyInt= (int)myChar;

    Typecasting is the process of changing a variable from one data type to another, in this case, from a char to an int.

References

  • Photo Credit Stockbyte/Stockbyte/Getty Images
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!