如何在C++中将值连接到其键

how concat a Value to its key in C++

本文关键字:连接 C++      更新时间:2023-10-16

我不知道如何写下我的问题,但我会尽力的。

说我使用C++语言:

我想得到下一个结果:

#include<iostream>
std::string line = "";
int lemmas = 1;
int main() {
    line = "<b>Lemma %d. <b>n"; // i want line = <b>Lemma 1. <b>n
    return 1;
}

如何添加它的值(在我的例子中是lemma)?

正如我的评论中所提到的,std::ostringstream类可以用来构造您想要的字符串:

#include <iostream>
#include <sstream>
std::string line = "";
int lemmas = 1;
int main() {
    std::ostringstream oss;
    oss << "<b>Lemma " << lemmas << ". <b>n"; // i want line = <b>Lemma 1. <b>nnn
    line = oss.str();
    return 1;
}

C++输出不像C printf()函数族那样使用格式化子句(例如%d)。

如果使用C++11,可以使用std::to_stringlemmas转换为字符串。

#include<string>
std::string line = "";
int lemmas = 1;
int main() {
    line = "<b>Lemma " + std::to_string(lemmas) + ". <b>n";
    return 1;
}

或者,如果Boost可用,你可以做一些类似于原始代码的事情:

#include <string>
#include <boost/format.hpp>
std::string line = "";
int lemmas = 1;
int main() {
    line = (boost::format("<b>Lemma %1%. <b>n") % lemmas).str();
    return 1;
}