CS253: Software Development with C++

Fall 2019

To String

Show Lecture.ToString as a slide show.

CS253 To String

to_string()

Example

string s;
s += to_string(0);     // int
s += to_string(1L);    // long
s += to_string(2LL);   // long long
s += to_string(3ULL);  // unsigned long long
s += to_string(4.5F);  // float
s += to_string(6.7);   // double
s += to_string(8.9L);  // long double
cout << s << '\n';
01234.5000006.7000008.900000

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 oss.str();
    }
}

int main() {
    try {
        foo(12, 1, 10);
    }
    catch (string msg) {
        cerr << "OOPS: " << msg << '\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 "Bad value " + to_string(n) + ", must be "
              + to_string(min) + "–" + to_string(max);
}

int main() {
    try {
        foo(12, 1, 10);
    }
    catch (string msg) {
        cerr << "OOPS: " << msg << '\n';
    }
}
OOPS: Bad value 12, must be 1–10

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