[英]How to paste vector elements into a string accordingly?
我使用的是 C++98,我有一个元素为13
m
1.5
0.6
的vector
,我想相应地将它们粘贴到这个字符串中。
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;
}
我想我明白你的意思,我会说你可以使用 printf 但因为你想使用cout
我建议使用有点像这样的逻辑:
#include <iostream>
#include <vector>
#include <string> //included string for find, length and replace
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 %v%v, weight is %vkg, friction coefficient = %v.";
string str2 = "%v"; //i have swapped the "%d" to make it a "%v", representating value, to make it not too similar to C
string final;
int valloc = 1; //if you ever decide to add more values to that vector
for (int i=0;i<4;i++) {
int oc = str.find(str2);
if (oc < str.length()+1 && oc > -1) {
final=str.replace(oc,2,values[i+(valloc-1)]);
}
}
std::cout << final;
return 0;
}
解释它的作用是:
1-需要一个字符串
2- 查找要替换的字符串%v
每次出现
3- 用向量中的适当值替换它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.