3.2 Combining Text and Numbers

You cannot just combine text and numbers in C++. As far as your computer knows, the values 42 and “42” have nothing to do with each other. The first one is an integer, the second one a string literal which happens to contain the characters 4 and 2.

Now, the Str class in Esenthel helps you a lot. It allows you to assign and add numbers to strings. For instance, all these expressions are correct:

 
int i = 42; 
Str myString =  42; 
myString    +=   i; 
myString    +=  42; 
5myString    += 4.2;  

But when you combine string literals (text between quotes) with numbers, you’re in trouble. The compiler will try to combine them first, before dumping them in a string. And it can’t do that. So this won’t work:

 
Str myString; 
myString = ”score: ” + 42; 
myString = 42 + ”score: ”;  

Without going into details here, there is a simple solution: a Str object called S is provided by Esenthel. Whenever you run into an error when you try to combine text and integers or floats, start with S +.

 
Str myString; 
myString = S + 42  + ” is your score”; 
 
int myScore = 10; 
5D.text(Vec2(0, 0), S + ”score: ” + myScore); 
 
// more complex 
D.text(Vec2(0, 0), S + ”score: ” + myScore + ” / 10”);  

Exercise
Create an application with an int ‘score’. Increase the score every time you press the space bar. Show the current score on the screen.