如何使用C ++ 17中的变量正确格式化输出中的字符串?

问题描述

我想知道什么是将字符串输出到带有变量的控制台的有效和聪明的方法。我知道在C ++ 20中有std :: format可以简化此操作,但是我不确定C ++ 17。

例如,可以在C ++ 20中完成:

#include <iostream>
#include <string>
#inclide <format>

int main(){

    int a = 13;
    int b = 50;
    std::string out_str = std::format("The respondents of the survey were {}-{} years old.",a,b);

    std::cout << out_str << std::endl;

    return EXIT_SUCCESS;

}

是否有一种类似于上述C ++ 17中示例的好方法?还是只需要将字符串和变量的不同部分分开?

解决方法

std::cout << "The respondents of the survey were " << a << "-" << b
   << " years old\n";

如果您发现冗长和/或令人讨厌,请使用fmtlib作为std::format的占位符。或与

一起上学
#include <cstdio>

std::printf("The respondents of the survey were %d-%d years old.\n",a,b);

这不是类型安全的,但是当格式字符串保留文字时,最近的编译器会很擅长将您指向不匹配的格式说明符和参数。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...