[英]How to paste vector elements into a string accordingly?
I'm using C++98, I have a vector
with the elements 13
m
1.5
0.6
and I would like to paste them into this 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 output will be输出将是
The length of Object 1 is 13m, weight is 1.5kg, friction coefficient = 0.6.
I tried it in a for loop but I'm not sure how to update the string after paste the 1st element.我在 for 循环中尝试过,但我不确定如何在粘贴第一个元素后更新字符串。 Any idea on this?
对此有什么想法吗?
Thanks for help.感谢帮助。
Edited:编辑:
The vector
and str
are just example. vector
和str
只是示例。 While, the number of element in vector
will always be the same as the number of delimiter (%d, %s, %f) in the 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;
}
I think I understood what you meant to do, I'd say you could use printf but since you want to use cout
I suggest using a logic somewhat like this:我想我明白你的意思,我会说你可以使用 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;
}
Explaining what it does is:解释它的作用是:
1- takes a string 1-需要一个字符串
2- finds every occurance of the string's %v
to replace 2- 查找要替换的字符串
%v
每次出现
3- replaces it with the proper value from the vector 3- 用向量中的适当值替换它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.