Section 9.12 Strings and Numbers
We already know that
123
is different than "123"
. The former is a number, the later a string. The type of data we are working with determines what operators we can use on it and what those operators do. Applied to integers, +
adds them and *
multiplies them. For strings, there is no definition for what *
means. That means it is a syntax error to try to write something like:
string message = "Hello";
string message2 = "world";
string x = message * message2; // syntax error. What does * mean here???
For
+
applied to strings, there is a definition - it does concatenation. So what happens if you try to mix data types? What happens if you +
an int
and a string
?
It turns out that in C++ that operation is not defined. And there is no easy way to modify the data so the operation makes sense. We can do
+
with an int
and a double
because the compiler knows that it is safe to turn any int into a double. But that is not true of strings. "hello"
is clearly not a number. Although it seems like "123"
could safely be converted to a number, what should happens with "42f"
or "7534759743912749237492"
(which is too large to store as an int). Because there is no guarantee that we can convert back and forth, the compiler will never try to do that for us.
Normally, if we want to tell the compiler to make a copy of something as a new type of data, we use
static_cast
. But a static_cast
assumes the compiler has a rule to do the conversion and is just reluctant to do so. The static cast is our way of saying βI know you think this is dangerous, I am sure I want to do it anyway.β But the compiler does not even have a general rule for converting back and forth from numbers to strings. So we canβt use static_cast
to do so.
Instead, we use
to_string
, stoi
, and stod
. to_string
takes any numeric value and returns a string representation of it. stoi
(string to integer) takes a string and tries to produce the integer value it represents. stod
(string to double) does the same thing with a double value.
to_string
is useful if you want to build up a string that contains a numeric value:
double width = 10;
double height = 25;
double area = width * height;
string message = "The area is ";
message += to_string(area);
message += " square units.";
Without
to_string
there would be a compiler error when we tried to add the numeric value area
to the string message
.
stoi
and stod
are useful if we need to do with math on numbers that were part of a string. This example takes a string in the format WIDTHxHEIGHT
and calculates the area:
You have attempted of activities on this page.