CS253: Software Development with C++

Spring 2020

To String

Show Lecture.ToString as a slide show.

CS253 To String

to_string()

Example

string s;
s += ' ' + to_string(false);                          // bool
s += ' ' + to_string('1');                            // char
s += ' ' + to_string(short(2));                       // short
s += ' ' + to_string(static_cast<unsigned short>(3)); // unsigned short
s += ' ' + to_string(4);                              // int
s += ' ' + to_string(5U);                             // unsigned int
s += ' ' + to_string(6L);                             // long
s += ' ' + to_string(7UL);                            // unsigned long
s += ' ' + to_string(8LL);                            // long long
s += ' ' + to_string(9ULL);                           // unsigned long long
s += ' ' + to_string(10.11F);                         // float
s += ' ' + to_string(12.13);                          // double
s += ' ' + to_string(14.15L);                         // long double
cout << s << '\n';
 0 49 2 3 4 5 6 7 8 9 10.110000 12.130000 14.150000

There’s no way to write short constants. 🤷

The old way

Before to_string(), error messages had to be created via a stringstream:

void foo(int n, int min, int max) {
    if (n < min || n > max) {
        ostringstream oss;
        oss << "Bad value " << n << ", must be "
            << min << "–" << max;
        throw range_error(oss.str());
    }
}

int main() {
    try {
        foo(12, 1, 10);
    }
    catch (const exception &e) {
        cerr << "OOPS: " << e.what() << '\n';
    }
}
OOPS: Bad value 12, must be 1–10

The new way

Now, error messages can be created via a to_string():

void foo(int n, int min, int max) {
    if (n < min || n > max)
        throw range_error(
                "Bad value " + to_string(n) + ", must be "
                + to_string(min) + "–" + to_string(max));
}

int main() {
    try {
        foo(12, 1, 10);
    }
    catch (const exception &e) {
        cerr << "OOPS: " << e.what() << '\n';
    }
}
OOPS: Bad value 12, must be 1–10

Better? You decide. It’s fewer lines of code, and no objects.