Wrox Programmer Forums Convert a char to int!!!!??
 |
 C++ Programming General discussions for the C++ language. For questions specific to Microsoft's Visual C++ variant, see the Visual C++ forum instead.
 Welcome to the p2p.wrox.com Forums. You are currently viewing the C++ Programming section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
October 2nd, 2005, 10:38 PM
 vtvb Registered User Join Date: Sep 2005 Posts: 2 Thanks: 0 Thanked 0 Times in 0 Posts
Convert a char to int!!!!??

why will this not work:

char x = '9';
int b;

b = int(x);

i get 57 not 9.

October 3rd, 2005, 03:00 AM
 Alan-LB Authorized User Join Date: Mar 2005 Posts: 58 Thanks: 0 Thanked 1 Time in 1 Post

Because 57 is the ASCII value for the character '9'

If you want to convert a character value for a number into an int you must subtract the value of the character zero ('0')

char x = 9; //Character '9' = ASCII 57
int b;

b = x - '0'; //That is '9' - '0' = 57 - 48 = 9

Alan

October 30th, 2005, 09:21 AM
 c_sky Registered User Join Date: Oct 2005 Posts: 2 Thanks: 0 Thanked 0 Times in 0 Posts

because char also return int

October 31st, 2005, 11:16 PM
 Alan-LB Authorized User Join Date: Mar 2005 Posts: 58 Thanks: 0 Thanked 1 Time in 1 Post

Yes - but in this case char x is set to '9' which is the Character 9 not the integer value 9. It is not a case of what char "returns" but what has been set in the variable.

In other words the character '9' has the integer value 57.

Alan

November 6th, 2005, 08:17 PM
 Paramesh Authorized User Join Date: Nov 2005 Posts: 21 Thanks: 0 Thanked 0 Times in 0 Posts

You can also take a look at the ASCII table to find more information.

November 6th, 2005, 10:22 PM
 middledd Authorized User Join Date: Nov 2005 Posts: 13 Thanks: 0 Thanked 0 Times in 0 Posts

you can use atoi() as well if you #include <cstdlib>

March 18th, 2006, 05:51 AM
 p0120144 Authorized User Join Date: Mar 2006 Posts: 12 Thanks: 0 Thanked 0 Times in 0 Posts

how to covert int to char

635467 = "635467"

 Similar Threads Thread Thread Starter Forum Replies Last Post Big challenge here! How to convert char* to char^? samiswt Visual C++ 2005 1 November 30th, 2007 09:09 PM How to Convert a int in a bool with FormatStrings ShadowMoon Classic ASP Basics 2 October 26th, 2004 05:53 AM Convert int to nvarchar bekim SQL Language 1 August 12th, 2004 06:33 AM Want to reiterate on my char to int problem CNewbie C++ Programming 0 April 2nd, 2004 12:47 AM convert char to int does not work yasaman C# 1 August 6th, 2003 10:39 AM