调用"替换(std::basic_string<char>::迭代器, std::basic_string::<char>迭代器, char, int)"没有匹配函数|
no matching function for call to 'replace(std::basic_string<char>::iterator, std::basic_string<char>::iterator, char, int)'|
如何将所有更改为
\
?
我想使地址用于处理文件:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "C:\user\asd";
replace(str.begin(), str.end(), '', '');
cout << str;
return 0;
}
我收到一个错误:
F:\c++\tests\regex\main.cpp|8|error: 调用 'replace(std::basic_string
:::iterator, std::basic_string ::iterator, char, int)'|
如何在 C++ 中使用char
数组(没有函数)完成这项工作?
您正在使用std::replace()
,它替换迭代器范围内的值。 在这种情况下,您使用的是来自std::string
的迭代器,因此要搜索的值和要替换它的值都必须是单个值char
。 但是,''
是多字节字符,因此不能用作char
值。 这就是您收到编译器错误的原因。
std::string
有自己的重载replace()
方法,其中一些方法可以用多字符字符串替换部分std::string
。
试试这个,例如:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "C:\user\asd";
string::size_type pos = 0;
while ((pos = str.find('', pos)) != string::npos)
{
str.replace(pos, 1, "\\");
pos += 2;
}
cout << str;
return 0;
}
现场演示
但是,您说您"想要创建地址来处理文件",这对我来说意味着您要创建一个file:
URI。 如果是这样,那么你需要更多类似的东西(这是一个严重的过度简化,一个合适的URI 生成器会比这个更复杂,因为 URI 有很多规则,但这将让你入门):
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
const char* safe_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@/";
int main()
{
string str = "C:\user\ali baba";
replace(str.begin(), str.end(), '', '/');
string::size_type pos = 0;
while ((pos = str.find_first_not_of(safe_chars, pos)) != string::npos)
{
ostringstream oss;
oss << '%' << hex << noshowbase << uppercase << (int) str[pos];
string newvalue = oss.str();
str.replace(pos, 1, newvalue);
pos += newvalue.size();
}
str = "file:///" + str;
cout << str;
return 0;
}
现场演示