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

标签 c++ string translate fizzbuzz

我正在尝试用 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();

当我在 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;
}

我收到此错误:

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

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

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

但我的问题是在 C++ 中是否有一种速记方式来执行此操作,就像在 JavaScript 中一样,还是我必须有类似于上面的 if 语句的东西?

最佳答案

在 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

那个三元例子等价于这个(假设在一个返回字符串的函数中):

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

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

  1. std::string 值为 "" (一个空字符串)不被认为是错误的, bool 明智的。通过stringName.length()查找字符串的长度,如果长度为0会返回0。
  2. :两边的返回类型必须相同,所以必须用std::to_string(i)将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;
}

关于c++ - 如果 C++ 中的一个变量为空,是否有一种速记方法来打印不同的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64383455/

相关文章:

c++ - 不用qmake编译Qt5代码

string - 从 HttpURLConnection 创建 InputStream 的副本,以便它可以使用两次

c++ - std string vs char performance,从一开始就删除部分的最佳技术

c++ - 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出?

c++ - 通过 NULL 指针访问类成员

c++ - 头文件中的类 - 无法编译?

c++ - 推导 Lambda 捕获类型

CSS:相对于父 div 进行翻译

java - 如何在java中使现有的多边形 move ?

Drupal 7 - 如何设置和翻译字段集合