You are here:

C++/C++ data types..

Advertisement


Question
i have a char variable... suppose
char a;
cin>>a;

and I input the character '46'...
is there any way to create an int variable and assign it to the number that the char variable is storing like...

int b;

b should have the value 46.  

Answer
Hello Karthik, thank you for the question.

Sure, you can get the integer value from a character. C++ provides the object istringstream for this.

char *a = "4690.4";
std::istringstream iss(a);
double value = 0.0;
iss >> value;

That will store the numerical value of the string contained by iss into the double named value. Also, there is an old C style way of doing this as well with a method named atof (remember it by ASCII to Float, atof, get it?):

char *a = "4567.9";
double value = atof(a);

This will store the numerical value of the string into the double value as well.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2012 About.com, a part of The New York Times Company. All rights reserved.