3

I'm trying to write a minified FizzBuzz program in C++ as I am just now learning it. I wondering if there's a shorthand way to say "If this string exists, return this string, otherwise, return this next part"

In JavaScript, using the || operator works the way I'm thinking of:

function fizzbuzz() {
  const maxNum = 20; // Simplified down to 20 just for example
  for (let i = 1; i <= maxNum; i++) {
    let output = "";
    if (i % 3 == 0) output += "Fizz";
    if (i % 5 == 0) output += "Buzz";
    console.log(output || i); // If the output has something, print it, otherwise print the number
  }
}

fizzbuzz();

When I try this in C++,

#include <iostream>
#include <string>
using namespace std;

int main() {
    int maxNum = 100;
    string output;
    for (int i = 1; i <= maxNum; i++) {
        output = "";
        if (i % 3 == 0) output += "Fizz";
        if (i % 5 == 0) output += "Buzz";
        cout << output || i << endl; // I've also tried the "or" operator instead of "||"
    }
    return 0;
}

I get this error:

main.cpp:12:32: error: reference to overloaded function could not be resolved; did you mean to call it?
        cout << output || i << endl;
                               ^~~~

I know that you can just say this before the cout (and change the cout line):

if (output == "") output += to_string(i);

But my question is just is there a shorthand way to do this in C++, like there is in JavaScript, or do I have to have something similar to the if statement above?

tadman
  • 208,517
  • 23
  • 234
  • 262
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • 3
    Hint: In C++ an empty `std::string` is not considered boolean `false`, however `output.length()` will be `0`. – tadman Oct 16 '20 at 05:40
  • @tadman When I try `cout << output.length() || i << endl;`, it gives the same error. When I wrap that in parentheses: `cout << (output.length() || i) << endl;`, it just prints out 100 "1"s. That seems to be because `i` is always greater than 0, so that boolean will always return `1` aka true. – Samathingamajig Oct 16 '20 at 05:45
  • 2
    Almost. Another hint: `output.length() ? ... : ...` Remember that in C++ boolean operations are really simple, they don't do anything fancy. `x || y` means that if `x` does not *evaluate as truthful*, as in is non-zero, then `y` is used instead. – tadman Oct 16 '20 at 05:45
  • @tadman ahh C++ has a ternary operator – Samathingamajig Oct 16 '20 at 05:46
  • 3
    Where do you think JavaScript got it from? (C++ got it from C). – tadman Oct 16 '20 at 05:46
  • @tadman `cout << (output.length() ? output : to_string(i)) << endl;` works! It doesn't work with just putting the `i`, because C++ is a strong typed language. (I'm kinda new to StackOverflow, if I find the correct answer do I put it as an answer to the actual question? or do you do it because you actually had the answer?) – Samathingamajig Oct 16 '20 at 05:49
  • 4
    Try a self-answer and explain a bit more about what you've learned so that'll help crystallize it. – tadman Oct 16 '20 at 05:50

1 Answers1

7

In C++, you can just use a ternary operator.

Ternary operators work like this (very similar to ternary in JavaScript):

condition   ? "truthy-return" : "falsey-return"
^ A boolean    ^ what to return   ^ what to return
  condition      if the condition   if the condition
                 is truthy          is falsey

That ternary example is equivalent to this (assume being in a function that returns a string):

if (condition) {
  return "truthy-return";
} else {
  return "falsey-return";
}

C++ does have its quirks since it is a statically typed language:

  1. std::string with a value of "" (an empty string) is not considered false, boolean wise. Finding the length of the string through stringName.length() will return a 0 if the length is 0.
  2. The return type of both sides of the : must be the same, so you must convert i into a string with std::to_string(i)
  3. Finally, this ternary operator must be inside of its own parentheses, like this: (output.length() ? output : to_string(i))

The code:

#include <iostream>
#include <string>
using namespace std;

int main() {
    int maxNum = 100;
    string output;
    for (int i = 1; i <= maxNum; i++) {
        output = "";
        if (i % 3 == 0) output += "Fizz";
        if (i % 5 == 0) output += "Buzz";
        cout << (output.length() ? output : to_string(i)) << endl;
    }
    return 0;
}
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34