簡體   English   中英

如何相應地將矢量元素粘貼到字符串中?

[英]How to paste vector elements into a string accordingly?

我使用的是 C++98,我有一個元素為13 m 1.5 0.6vector ,我想相應地將它們粘貼到這個字符串中。

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 循環中嘗試過,但我不確定如何在粘貼第一個元素后更新字符串。 對此有什么想法嗎?

感謝幫助。

編輯:

vectorstr只是示例。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM