char + int => int / Problem with cout

Hey Guys,

I'm pretty new to C++. Earlyer did a bit python so I'm not that precise as I should be in cpp I guess.

Following code always gives me the Output you see on the bottom.
I

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Hero::Hero(string hname, int health, int mana, int atk, int def){
	hname_ = hname;
	health_ = health;
	mana_ = mana;
	atk_ = atk;
	def_ = def;

}

void Hero::heal(int amounth){
	health_ += amounth;
	if (health_ >= 100){
		health_ =100;
	}
	cout << hname_ + " was healed by " + (char)amounth + " and his health is now " + (char)health_ << endl;

}

cout << hname_ + " was healed by " + (char)amounth + " and his health is now " + (char)health_ << endl;


Dieter was healed by  and his health is now d


I'm trying to add chars to ints by assigning them as char variables for the cout. If i put them ints again it returns an error message.

I already looked around a little and normally an int + char should remain an int, shouldn't it?

Tipps please. :)

Why not change them to int across the board?
because you are trying to concatenate strings "+"

try this instead
cout << hname_ << " was healed by " << amounth << " and his health is now " << health_ << endl;
derp yea, Jay is right
You can't add an int to a string, that's why you get the error message without casting to char.

But when you cast to char, you're converting the heath improvement (presumably between 0 and 100), into a single ASCII character. For example, if you add 32 to health, then (char)amounth is a space.

You need to output the different types separately:
cout << hname_ << " was healed by " << amounth << " and his new health is now " << health_ << endl;
Note that this also more efficient because you aren't creating a bunch of temporary strings.
Argh!!!

You are so right. Too much python during the last weeks.

Thank you very much.
Don't forget to mark as solved!

Have fun programming
Topic archived. No new replies allowed.