【发布时间】:2021-02-20 11:45:52
【问题描述】:
我正在使用 C++98,我有一个 vector 和元素 13 m 1.5 0.6 我想将它们相应地粘贴到这个字符串中。
The length of Object 1 is %d%s, weight is %dkg, friction coefficient = %f.
输出将是
The length of Object 1 is 13m, weight is 1.5kg, friction coefficient = 0.6.
我在 for 循环中尝试过,但不确定如何在粘贴第一个元素后更新字符串。对此有什么想法吗?
感谢您的帮助。
已编辑:
vector 和 str 只是示例。而vector 中的元素数量将始终与str 中的分隔符数量(%d、%s、%f)相同。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> values;
values.push_back("13");
values.push_back("m");
values.push_back("1.5");
values.push_back("0.6");
string str = "The length of Object 1 is %d%s, weight is %dkg, friction coefficient = %f.";
string str2 = "%d";
string str_crop;
string unk;
string final;
size_t found = str.find(str2);
if (found != std::string::npos)
{
str_crop = str.substr(0, found);
}
for (int i = 0; i < values.size(); i++) {
unk = values[i];
str_crop += unk;
}
final = str_crop;
cout << final << endl;
return 0;
}
【问题讨论】:
-
请出示您的代码,minimal reproducible example
-
假设您出于某种原因必须在代码中使用 C 格式说明符,请查找
std::sprintf()(但请记住检查所需的缓冲区长度为sprintf()假设它正在写入足够长的缓冲区,并且如果该假设不正确,则具有未定义的行为)。在 C++ 中(不同于在 C++ 中使用 C 技术)使用std::ostrstream。 -
@idclev463035818 嗨,代码已添加。
-
格式化选项是否有意义,因为您的输入是
std::string?
标签: c++ string for-loop vector paste