Convert string number to Int

I know this is a very newb question to ask and all, but is it possible to convert a number in a char or string variable into an int variable?

in effect I want to do this;

Int x = 12;
char y = "2";

x += y;

cout<<x<<endl;


to where the result would be 14 without any error messages going off about strings not converting to int's.
1
2
3
4
5
6
7
8
#include <cstdlib>  //required for use of atoi, atof, aotll functions

int x = 12;
char y = "2";

x += std::atoi(y);  // Use the integer equivalent of char / string  y;

std::cout << x << std::endl;
You can also use std::stoi in C++11
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
	int x = 12;
	std::string y = "2";

	x += std::stoi(y);

	std::cout << x << std::endl;
}

Great, thanks for the help, I'll apply this to my code as soon as I get back home.
Thank you.
Integer to char is very easy (0-9)
beyond that it will not be possible to store an integer in a char, instead you will need a bigger space, array of char etc. and then you will have to do a bit more work.

integer 0 (zero) = char 49 (Ascii)

1
2
3
4
5
6
7
8
9
10
11
12
int x; // x is the integer value

/***************
* int 0 = char 49   *
* int 1 = char 50   *
* int 2 = char 51   *
* int 3 = char 52   *
* int 4 = char 53   *
* and so on.......  *
***************/

char c = 49+x;  // c will be the char of x  
Last edited on
http://www.cplusplus.com/doc/ascii/

this gives the entire table, but its in HEXADECIMAL
Hope you know what is HEX, just incase, HEX is base 16

Decimal=HEXADECIMAL
0=0
1=1
2=2
3=3
4=4
5=5
6=6
7=7
8=8
9=9
10=A
11=B
12=C
13=D
14=E
15=F
16=10
Last edited on
Topic archived. No new replies allowed.