Hello guies please help me
how can I typecast string to char

Recommended Answers

All 6 Replies

you can't because you can't stuff a whole string into a single character. If this is about some error message you got, then post the error message along with the code you wrote.

A string cannot be cast to a char, because a char is one byte and a string can be any number of bytes. You can, however, use std::string's c_str member and create a const char* out of your string.

string s = "hi";
const char *cs = s.c_str();

This can be useful if you want to copy the value into a character array, which might look like this:

string s ="hello";
char carr[6]; // note the size, leave room for \0
strcpy( carr, s.c_str() );

Or, if you want to return a single character from a string you can either use the [] operator or the at member.

string s = "hello";
cout << s[0]; // prints 'h'
cout << s.at(1); // prints e

Do you mean string to char* ? You could access the c_str() , which is of type const char*.

ok , can I typecast string into double?

I want to convert string 12.12 to double 12.12

ok , can I typecast string into double?

I want to convert string 12.12 to double 12.12

You can do this using stringstreams, as long as you validate the string first to make sure that it is in-fact a double value, otherwise your program will crash. An explicit cast of string to double is not supported, however.

OMG NO !!! You should NEVER typecast a string to a numeric type. Use something like strtod() to convert a char* to a double, or use stringstream, see here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.