Skip to main content
gamedev.net
🔒 Locked

Input problems...

Started by RegularKid 4 replies 150+ views
Original Post
RegularKid
RegularKid
How do i (in C++) convert from a char to integer? example: input : ''5'' <-- char output: 5 <-- int
Oluseyi
Oluseyi
cin handles the conversion automatically:

#include &ltiostream>

using namespace std;
int main( int argc, char *argv[] )
{
char c;
int i;
cout << "Input an integer: ";
cin >> i;
cout << i << endl << "input a character: ";
cin >> c;
cout << c << endl;
}

The funny thing is that you can read a character into an integer variable and vice-versa, because all they are is memory locations of different sizes.
Dactylos
Dactylos
To convert from a single char (''containing'' an integer value) to an integer value you can do

  
char ch = ''8'';
int val = ch - ''0'';
// now val will contain the integer value 8


(i.e. Just subtract ''0'' from it)

To convert a string (''containing'' an integer) to an integer value you can use atoi() or sscanf()

ex.
  
char * str1 = "248";
int val1 = atoi(str1);
// now val1 will contain the integer value 248


char * str2 = "7356";
int val2;
sscanf(str2, "%d", &val2);
// now val2 will contain the integer value 7356


RegularKid
RegularKid
char ch = ''8'';
int val = ch - ''0'';
// now val will contain the integer value

Cool! That worked great. Is there a way to change the integer back into a char?:

example:

input = 8 <-- int
output = ''8'' <--char
Martee
Martee
Just do the opposite of what Dactylos said. Add ''0'' to it.
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
RegularKid
RegularKid
Hmmm. This works good for 1 digit numbers, but what about 2 digit numbers?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.