首页 > 解决方案 > std::string::insert 不适用于 to_string()。CPP

问题描述

我正在编写一个代码来在字符串的索引处插入一个整数,但是在提供要添加为字符串的整数之后,插入函数没有给出正确的输出。

它给出的错误是:

没有匹配的成员函数来调用插入字符串

这是我的代码:

#include <iostream>
using namespace std;

int main()  
{
    string s = "45564528";
    int x = 8;
    s.insert(s.begin()+5,to_string(x));
    cout<<s<<endl;
   
    return 0;
}

预期输出为 455648528。

标签: c++

解决方案


查看文档表明std::string::insert()它需要 achar或迭代器范围,而不是 a std::string,它std::to_string()自然会返回。至少,对于第一个参数采用迭代器的重载就是这种情况。

#include <iostream>
#include <string>  // CHANGED: Include what you use

// using namespace std;  // CHANGED: Bad practice

int main()
{
    std::string s = "45564528";
    int x = 8;

    // CHANGED: Create string from the int, and use the iterator range overload
    // to account for multi-digit numbers
    auto tmp = std::to_string(x);
    s.insert(s.begin()+5, tmp.begin(), tmp.end());
    std::cout << s << '\n';  // CHANGED: std::endl is rarely actually needed

    return 0;
}

有一个重载可以让你插入另一个std::string,但第一个参数必须是索引而不是迭代器。所以这也可以:

#include <iostream>
#include <string>

int main()
{
    std::string s = "45564528";
    int x = 8;

    s.insert(5, std::to_string(x));
    std::cout << s << '\n';

    return 0;
}

推荐阅读