Reputation: 965
How can I convert a string to char?
I already Googled and I didn't find the answer to the situation I'm in. Really, I'm trying to convert an int to a char but my compiler doesn't support the to_string function so I decided to convert to from int to string then string to char.
I'm using a char[ ][ ] so I can store integers and chars.
stringstream ss;
ss << j; // j is the integer
string s(ss.str());
ascii_text[1][i] = (char)s;
EDIT:
I'm working with ASCII chars.
This is what I'm trying to do. int a = 10; -> string s = "10"; -> char c = '10';
I'll be happy if I found a way to convert int to char directly.
Upvotes: 1
Views: 3899
Reputation: 9071
How can I convert a string to char?
Okay. If you mean char*
, then the std::string
class has a c_str()
method:
std::string myString = "hello";
const char* myStr = myString.c_str();
A char
has a size of 1 byte, so you can't fit any string in it, unless that string has a length of 1. You can however get the char at a certain position in a string:
std::string str = "hi bro";
char c = str[0]; // This will be equal to 'h'
Upvotes: 3
Reputation: 3912
You can use the c_str() method to get an array of chars from string.
http://www.cplusplus.com/reference/string/string/c_str/
Upvotes: 0
Reputation: 15683
If I understood you correctly, then all you want to do is get from an integer digit (0-9) to an ascii digit ('0'-'9')? In that case, char(j)+'0'
will do.
Upvotes: 3
Reputation: 3766
You should be able to just do
int j = 3;
char ch;
stringstream ss;
ss << j;
ss >> ch;
Upvotes: 0