Connecting Tech Pros Worldwide Forums | Help | Site Map

Convert char to integer

Member
 
Join Date: Jul 2007
Location: The Earth
Posts: 115
#1: Jul 17 '07
Is it possible to convert a char to an int or reverse.
eg. int x = 12345
is it pssible to make char y[10] = "12345" without user input?

zodilla58's Avatar
Expert
 
Join Date: Dec 2006
Posts: 783
#2: Jul 17 '07

re: Convert char to integer


Quote:

Originally Posted by Firecore

Is it possible to convert a char to an int or reverse.
eg. int x = 12345
is it pssible to make char y[10] = "12345" without user input?

You can do like this:
Expand|Select|Wrap|Line Numbers
  1. int i = 12345;
  2. char c = static_cast<char>(i);
  3.  
OR
Expand|Select|Wrap|Line Numbers
  1. int a = 12345;
  2. char * b= new char [50];                        
  3. itoa(a, b, 10); //b will now contain the value you want as a string
  4.  
Regards
ilikepython's Avatar
Expert
 
Join Date: Feb 2007
Posts: 839
#3: Jul 17 '07

re: Convert char to integer


Quote:

Originally Posted by zodilla58

You can do like this:

Expand|Select|Wrap|Line Numbers
  1. int i = 12345;
  2. char c = static_cast<char>(i);
  3.  
OR
Expand|Select|Wrap|Line Numbers
  1. int a = 12345;
  2. char * b= new char [50];                        
  3. itoa(a, b, 10); //b will now contain the value you want as a string
  4.  
Regards

The C++ way is using a stringstream object:
Expand|Select|Wrap|Line Numbers
  1. #include <sstream>
  2. int a = 12345;
  3. string astr;
  4. stringstream ss;
  5. ss << a;
  6. ss >> str; // str now contains 12345 as a string
  7.  
Member
 
Join Date: Jul 2007
Location: The Earth
Posts: 115
#4: Jul 17 '07

re: Convert char to integer


Thanx for that.
I think i will stick to the c method.
I do not know how to use C++
Reply