Is there an easy way to convert from Char* to int? I have tried converting as such:

char* value_a;
int* temp = value_a;
int final = temp;

The compiler is returning an error so I know something is wrong but why can't I convert this way? Any suggestions as to how to easily convert from char* to int. (Even char* to int* would get me closer) I need to be able to carry out simple calculations on the final variable. Thank you!

Dani AI

Generated

The code in the first post is treating a pointer as if it were the numeric value encoded by the characters. A char* holds an address; casting or assigning it to an integer type produces the pointer value (an address) and is implementation-defined/portable only in limited ways — it does not parse the digits in the string. ('s snippet and 's suggested cast illustrate that confusion.) Pointer-to-integer conversions are described here.

What is needed is string-to-number parsing, not pointer casting. Options (short summary):

  • atoi exists but does not report errors reliably (overflow is undefined). See notes on atoi. (This is the issue / were weighing and flagged.)
  • strtol (C) gives an end-pointer and uses errno so failures and overflow can be detected; recommended for C code. See strtol.
  • std::stoi (C++11) throws exceptions on bad input or out-of-range; convenient for std::string users. See std::stoi.
  • std::from_chars (C++17) is the modern choice: non-allocating, non-throwing, fast, and gives precise error codes — good when parsing const char* / buffers. Note it does not skip leading whitespace. See std::from_chars.

Example (C++17): valid, low-overhead parsing of a char* to int using from_chars:

#include <charconv>
#include <cstring>
#include <system_error>

const char* s = "123456";
int value = 0;
auto res = std::from_chars(s, s + std::strlen(s), value, 10);
if (res.ec == std::errc()) {
    // success: 'value' contains the parsed integer
} else if (res.ec == std::errc::invalid_argument) {
    // not a number
} else if (res.ec == std::errc::result_out_of_range) {
    // value too large for 'int'
}

Practical tips: always check for null pointers and whether the conversion consumed the expected characters (end pointer or pos). If targeting older compilers, use strtol with errno/end-pointer checks. Streams (std::istringstream) work too (they were suggested by ) but are heavier and locale-dependent compared to from_chars.

Recommended Answers

All 9 Replies

Why do you want to convert a character pointer to an integer? Such conversion are normally not done.

But the answer is int final = (int)value_a;

Are you trying to convert a string of digits to a number you can do calculations with? If so, you can you atoi().

You can use also to convert to int

int final;
stringstream strm;
char * value_a = "123456";

strm << value_a;
strm >> final;

You can use also to convert to int

int final;
stringstream strm;
char * value_a = "123456";

strm << value_a;
strm >> final;

I never knew about that. This looks great

Or simply use old good atoi() from <cstdlib>:

char* value_a = "123456";
int final = std::atoi(value_a);

Old, yes. Good, not a chance!
It can't even detect integer overflow.

I think, at this level of the programming skill atoi() is a suitable solution. For example, stringsteam solution (see above) does not check the result too.
Maniacally check this, check that == not to see the wood for the trees ;)...

Why is it so hard to tell people about the best way of doing it, rather than some old hack which they'll have to unlearn sooner or later?

It's not like there's a massive difference in line count (or anything) between the two.

stringstream (the basics of it) takes no more explaining that explaining atoi would. Probably less, if you exclude all the caveats.

commented: Logic might get us not very far in this one. +9

To Salem:
Formally you are right, but...
To be honest we must write tons of words, for example:

// ... don't forget to check conversion result...
// ... better write a function ...
bool getInt(int& target, const char* source)
{
    bool ok = false;
    if (source)
    {
        std::istringstream istr(source);
        if (istr >> target)
            ok = true;
    }
    return ok;
}
// ... or use strtol() ...
char stopchar;
final = static_const<int>(std::strtol(value_a,&stopchar,10));
if (std::errno == ERANGE)
   ...
// ... or use C++ exception to signal overflow or bad data ...
   ...

And so on...
What's an awful answer to the simplest (in addition incorrectly formulated;)) question!
It seems the only result of that explanation: the burnt child dreads the fire (or C++;))...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.