Converting a int to a char

May 6, 2012 at 10:56pm
Hello!

I've run into a problem when I'm trying to insert an int into a string. I'm using the string::insert()-method for this which only accepts a char argument. All the methods which I have used, itoa, stringstreams and so on, only seem to return a char-pointer, which does not work out.

So what I want to do is pretty much
mystring.insert(mystring.begin(), 1, myint(as a char));

Thank you in advance!
May 6, 2012 at 11:03pm
well I can't see a problem in passing myint as it is?! Have you tried to do so and got a error or somthing?!
May 6, 2012 at 11:10pm
Integers are often more than one character, so you can't pass one to insert into a string. You could use atoi to get a C-string, then insert each character, I suppose.
May 6, 2012 at 11:10pm
You can do an explicit cast: mystring.insert(mystring.begin(), 1, (char)myint));. But an integer will implicity cast into a char so I cant really see an issue. Rembmer than an int is always bigger than a char so the value of your int may not fit into the char properly.
Last edited on May 6, 2012 at 11:12pm
May 6, 2012 at 11:13pm
That will work, but it won't do what OP intended. Casting to a char will give you the character at that ASCII value, not insert the numbers as characters.
May 7, 2012 at 8:12pm
None of the above works out, or I'm simply doing it the wrong way. Here's an example:

string Output;
if(_iNumber < _iBase)
{
char * lechar = NULL;
itoa (_iNumber, lechar, 10);
Output.insert(Output.begin(), 1, lechar);
}

Output.insert() will complain about lechar as an argument because it is of type * char.
Another example:

string Output;
if(_iNumber < _iBase)
{
char lechar;
itoa(_iNumber, lechar, 10);
Output.insert(Output.begin(), 1, lechar);
}

itoa() will complain about lechar as an argument because it is of type char and not * char.

I really feel that this shouldn't be so hard. :(
May 7, 2012 at 10:26pm
Example :
1
2
3
4
5
6
7
8
9
10
11
12
13
	std::string str = ", hello";
	int h = 123456;
	std::string h_string;
	//conversion
	std::stringstream s;
	s<< h;
	s>>h_string;
	//inserting
	for(std::string::reverse_iterator it = h_string.rbegin(); it != h_string.rend();++it)
	{
		str.insert(str.begin(),*it);
	}
	std::cout<<str;
May 7, 2012 at 10:38pm
Try this:
1
2
3
std::ostringstream ss;
ss << mystring << myint;
mystring = ss.str();


If you are using C++11 you can also try this:
mystring = std::to_string(myint) + mystring;
Last edited on May 7, 2012 at 10:39pm
May 7, 2012 at 11:02pm
What if he wanted to insert at a certain pos in string.

Another example but thise use size_t pos not iterators:
1
2
3
4
5
6
7
std::string str = ", hello";
	int h = 12122;
	char h_string[33];// max bits for a integer on 32-bit
	//;
	sprintf(h_string,"%d",h);// or _itoa(h,h_string,10)
	//inserting
	str.insert(0,std::string(h_string));
Topic archived. No new replies allowed.