Convert a character to an integer in C++

23,819

Solution 1

Yes -- in C and C++, char is just a small integer type (typically with a range from -128 to +127). When you do math on it, it'll normally be converted to int automatically, so you don't even need your cast.

As an aside, you really don't want to use strlen(s) inside the stopping condition for your for-loop. At least with most compilers, this will force it to re-evaluated strlen(s) every iteration, so your linear algorithm just became quadratic instead.

size_t len = strlen(s);

for (int i=0; i<len; i++)
    Sum += s[i];

Or, if s is actually a std::string, as the parameter type suggests:

for (int i=0; i<s.size(); i++)
    Sum += s[i];

As yet one more possibility:

Sum = std::accumulate(s.begin(), s.end(), 0);

Solution 2

Characters are usually represented internally by integers, so s[i] can be assigned to an integer.

If you have char '1', and want to store int 1, then you can do s[i]-'0'.

Solution 3

You might be looking for

Sum += s[i] - '0';

For the general case of converting numbers to strings and vice versa see this FAQ entry.

Share:
23,819
OurFamily Page
Author by

OurFamily Page

Updated on October 19, 2020

Comments

  • OurFamily Page
    OurFamily Page over 3 years

    How can I set each character in a string to an integer? This is just the first thing I have to do in order to write a hash function. I have to set each character in a string to an integer so that I can sum their values. Please help! It it something like this??

        int hashCode(string s)
    {
       int Sum = 0;
       for(int i=0; i<strlen(s); i++)
       {
          Sum += (int)s[i];
       }
       return Sum;
    }