如果 C++ 中的一个变量为空,是否有一种速记方法可以打印不同的变量?

Sam*_*jig 3 c++ string fizzbuzz translate

我正在尝试用 C++ 编写一个缩小的 FizzBu​​zz 程序,因为我现在正在学习它。我想知道是否有一种速记方式可以说“如果此字符串存在,则返回此字符串,否则,返回下一部分”

在 JavaScript 中,使用||运算符的工作方式与我想的一样:

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();
Run Code Online (Sandbox Code Playgroud)

当我在 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;
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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

我知道你可以在cout(并更改 cout 行)之前说这个:

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

但我的问题是在 C++ 中是否有一种速记方法可以做到这一点,就像在 JavaScript 中一样,或者我是否必须有类似于if上面的语句?

Sam*_*jig 7

在 C++ 中,您可以只使用三元运算符。

三元运算符的工作方式如下(与 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
Run Code Online (Sandbox Code Playgroud)

该三元示例与此等效(假设在返回字符串的函数中):

if (condition) {
  return "truthy-return";
} else {
  return "falsey-return";
}
Run Code Online (Sandbox Code Playgroud)

C++ 确实有其怪癖,因为它是一种静态类型语言:

  1. std::string值为""(空字符串)不被认为是错误的,布尔明智的。stringName.length()如果长度为 0 ,则通过查找字符串的长度将返回 0。
  2. 两边的返回类型:必须相同,所以必须转换i成字符串std::to_string(i)
  3. 最后,这个三元运算符必须在它自己的括号内,像这样: (output.length() ? output : to_string(i))

编码:

#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;
}
Run Code Online (Sandbox Code Playgroud)