Cast a char to int (actual numeric value)

Sorry if this topic has been posted a million times over, but I’m having some problems getting a character (that’s a number) into an int. And by that, I want the actual numeric value, not the ASCII value which is what I keep getting. Is there a simple, standard way to do this in C++?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

int getCredits(std::string);

int main()
{

	std::string testString = "1234";
	std::cout << getCredits(testString) << std::endl; //outputs '50'
	return 0;
}

int getCredits(std::string s)
{
	return static_cast<int>(s.at(1));
}
If you're asking what I think you're asking, you can just subtract '0':

1
2
3
char c = '3';
int n = c - '0';
// n == 3 


This is only good for a single digit number and you are responsible for bounds checking.
Last edited on
That'll work. Appreciate it! :)
You can also do -48 I believe if you want to save 1 char of typing
Topic archived. No new replies allowed.