Home > Software design >  How to convert int to string in a ternary operation
How to convert int to string in a ternary operation

Time:10-07

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)

CodePudding user response:

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.

CodePudding user response:

To do that int the same line, try:

for (int num = 0; num < 100; num  ) {
    cout << (num % 10 == 0 ? "Divisible by 10" : to_string(num)) << endl;
}
  • Related