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?