1

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.

MosesA
  • 925
  • 5
  • 27
  • 53

4 Answers4

3

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.

Cubic
  • 14,902
  • 5
  • 47
  • 92
  • Have to add tens places too http://stackoverflow.com/a/7022827/195488 , if going to int –  Mar 25 '13 at 20:16
  • @Cubic I already tried that and I got ASCII chars, like 20 would give be space instead of '20'. – MosesA Mar 25 '13 at 20:25
  • @AdegokeA That's because there's no character for the number 20. If you want a string, then you just take the string you already got. – Cubic Mar 25 '13 at 20:26
  • I'm using a char[][] so I can store integers and chars. See my problem? – MosesA Mar 25 '13 at 20:28
  • @AdegokeA No, I don't. I don't know what you're trying to do, but I think you're doing it wrong. – Cubic Mar 25 '13 at 20:39
  • Yeah, I am. I didn't have to use a 2D array. Thanks though. :) – MosesA Mar 25 '13 at 20:42
3

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'
user123
  • 8,970
  • 2
  • 31
  • 52
0

You should be able to just do

int j = 3;
char ch;
stringstream ss;
ss << j;
ss >> ch;
DiegoNolan
  • 3,766
  • 1
  • 22
  • 26
0

You can use the c_str() method to get an array of chars from string.

http://www.cplusplus.com/reference/string/string/c_str/

Johnny Mnemonic
  • 3,822
  • 5
  • 21
  • 33