Search code examples
c++stringcastingtype-conversionconditional-operator

How to convert int to string in a ternary operation


When trying to do a ternary operation using an integer and string such as:

for (int num = 0; num < 100; num++) {
    cout << (i % 10 == 0) ? "Divisible by 10" : num;
}

You end up with the following exception

E0042: operand types are incompatible ("const char*" and "int")

If you were to try to cast num to const char* by doing (const char*)num you will end up with an access violation. If you do (const char*)num& instead, you get the ASCII character corresponding to the value.

For numbers greater than 10 how can you quickly cast that integer into a string? (Preferably in the same line)


Solution

  • If you insist on the conditional operator, you could write this:

    for (int num = 0; num < 100; num++) {
        (num%10==0) ? std::cout << "Divisible by 10" : std::cout << num;
    }
    

    If you want to stay with yours, you need to convert the values to some compatible types. There is no way around that. The conditional operator is not an equivalent replacement for an if-else statement and often the latter is much clearer:

    for (int num = 0; num < 100; num++) {
        if (num%10==0) { std::cout << "Divisible by 10"; }
        else { std::cout << num; }
    }
    

    For numbers greater than 10 how can you quickly cast that integer into a string? (Preferably in the same line)

    std::to_string can convert numbers to strings.


    PS: To illustrate an example where an if-else cannot be used and the conditional operator is actually useful, consider the initialization of a reference. You cannot write:

    int x = 0;
    int y = 0;
    int& ref;    // nope, error
    if (condition) ref = x;   
    else ref = y;
    

    but you can write:

    int& ref = (condition) ? x : y;
    

    There are other cases where the conditional operator is useful. It's purpose is not just to save a line of code compared to an if-else.