Hello all,
I am new to this board but I am not that new to C++. And I know other programming and scripting languages well.
My problem is to convert a
std::string to
char (neither
char* nor
char[]) as a
numeric value. Converting to an
int or
long seems quite easy together with
std::stringstream and I got that part working already.
When I try to do the same with char it looks like only the first character in the string is copied to the
char variable as an ASCII coded character. Here is a short example, code below:
I want to convert the
std::string "42" to a
char of numeric value 42. What I get is a
char of value 52 which is the ASCII Code for "4" the first character of "42". Other values for the
std::string show the same symptom.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
char c = 42;
std::string str("42");
std::stringstream sstr;
// before conversion
std::cout << c << std::endl; // outputs "*" (ASCII Code 42)
std::cout << (int) c << std::endl; // outputs "42" (ASCII Code for "*")
std::cout << str << std::endl; // outputs "42"
// string to number conversion - not working as wanted
sstr << str;
sstr >> c;
// after conversion
std::cout << c << std::endl; // outputs "4" (ASCII Code 52)
std::cout << (int) c << std::endl; // outputs 52 (ASCII Code for "4")
|
I tried many things to solve this problem. Some led to syntax errors others had no effect at all. The best thing I got was to convert only the first character as seen above.
I have searched Google, the reference and the forums for a solution to this problem but I only found topics about converting different string types to other numeric types (
int,
long ...) or vice versa.
For me it looks like
std::stringstream is handling
char as a real single character and not as a numeric value. But I don't know if that is true. If this is the case is there an easy way to have this solved without C style typecasting or a temporarily
int?
I am sorry for this long post for this small problem but I wanted to make clear what kind of conversion I need.
Best regards
linxard.