I know this is probably pretty basic and makes you wonder why I didn't look it up, but I did look it up. Unfortunately, everything I found was how to change a char to it's ASCII value.
So, how can I change '7' (a char), for example, to 7 (an int)?
Help would be appreciated, thanks!
Edit: I know how to change a string to an int. However, changing a char to a string then to an int doesn't seem to work.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
char ex = '5';
int n;
string str = to_string(ex);
n = stoi(str);
cout << n;
}
Subtract '0' (the character zero) from '7' to yield the int 7.
static_assert(7 == '7' - '0');
This will work because it is guaranteed that the character codes representing the digits 0-9 are contiguous and in order. There is no such guarantee for any other group of characters. In particular, the character codes for the letters a-z and A-Z don't necessarily have this behavior, so you can't assume in general e.g. static_assert(2 == 'c' - 'a');
Although that assertion is usually true.
easier than my += with std::string? Its virtually identical, apart from c string vs c++ string?
the issue looks like tostring. Regardless -'0' is the most efficient, involving data structures and functions is just overhead.
<cstdlib> has functions to convert C strings to numeric types. They take C string char arrays as parameters, as well as char variables. For char variables you pass the address of the variable.
<cstdlib> has functions to convert C strings to numeric types. They take C string char arrays as parameters, as well as char variables. For char variables you pass the address of the variable.
...
Thank you for your response too! I see what I did wrong while trying to use stoi and I've fixed it. I've also bookmarked this page for future reference of the various ways this can be solved. :)