简体   繁体   中英

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.

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. Any idea on this?

Thanks for help.

Edited:

The vector and str are just example. While, the number of element in vector will always be the same as the number of delimiter (%d, %s, %f) in the str .

#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:

#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

2- finds every occurance of the string's %v to replace

3- replaces it with the proper value from the vector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM