【问题标题】:How to paste vector elements into a string accordingly?如何将矢量元素相应地粘贴到字符串中?
【发布时间】: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 循环中尝试过,但不确定如何在粘贴第一个元素后更新字符串。对此有什么想法吗?

感谢您的帮助。

已编辑:

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;
}

【问题讨论】:

  • 请出示您的代码,minimal reproducible example
  • 在 C++ 中,您可以使用 boost format 库。在 C 语言中,您可以使用 sprintf
  • 假设您出于某种原因必须在代码中使用 C 格式说明符,请查找 std::sprintf()(但请记住检查所需的缓冲区长度为 sprintf() 假设它正在写入足够长的缓冲区,并且如果该假设不正确,则具有未定义的行为)。在 C++ 中(不同于在 C++ 中使用 C 技术)使用 std::ostrstream
  • @idclev463035818 嗨,代码已添加。
  • 格式化选项是否有意义,因为您的输入是std::string

标签: c++ string for-loop vector paste


【解决方案1】:

我想我明白你的意思,我想说你可以使用 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- 用向量中的正确值替换它

【讨论】:

  • 有帮助吗?
猜你喜欢
  • 2021-07-27
  • 2020-01-07
  • 2011-10-22
  • 2016-11-16
  • 2019-11-07
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
相关资源
最近更新 更多