gpt4 book ai didi

c++ - string::erase 不接受迭代器?

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:38 26 4
gpt4 key购买 nike

我在使用带迭代器的字符串函数 erase 时遇到问题。

下面的函数采用输入文件和 .ini 文件的名称,并创建输出文件的路径。路径定义为

dir + in_file + def_name + ini_file + ".txt"

我正在使用 erase 删除输入文件名的扩展名。

void Output::vDefault(string in, string ini)
{
//save names
strIn=in;
strIni=ini;

//get working dir
char mydirectory[MAX_PATH] = {""};
GetCurrentDirectory(MAX_PATH,mydirectory);

//erase extensions
strIn.erase(strIn.find_last_of('.'), strIn.end()); // error
strIni.erase(strIni.find_last_of('.'), strIni.end()); // error

//adr starts with folder
strAdr=mydirectory;
//and ends with name
//address=dir+in_file+def_name+ini_file+.txt;
strAdr+=strIn+DEFOUTNAME+strIni+".txt";
}

运行代码会导致以下错误:

error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::erase(unsigned int,unsigned int)' : cannot convert parameter 2 from 'std::_String_iterator<_Elem,_Traits,_Alloc>' to 'unsigned int'

erase 可以将两个迭代器作为 first 和 last。你能帮助我吗?我不知道为什么它在我的项目中不接受除 int 之外的任何内容。

最佳答案

错误发生是因为删除签名需要 2 个 size_t 或 2 个迭代器。不是组合。find_last_of 返回一个 size_t

http://www.cplusplus.com/reference/string/string/erase/

string& erase ( size_t pos = 0, size_t n = npos );
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );

http://www.cplusplus.com/reference/string/string/find_last_of/

size_t find_last_of ( const string& str, size_t pos = npos ) const;
size_t find_last_of ( const char* s, size_t pos, size_t n ) const;
size_t find_last_of ( const char* s, size_t pos = npos ) const;
size_t find_last_of ( char c, size_t pos = npos ) const;

解决方案是使用

string& erase ( size_t pos = 0, size_t n = npos );

这里size_t n 是可选的。

Erases a sequence of n characters starting at position pos. Notice that both parameters are optional: with only one argument, the function deletes everything from position pos forwards, and with no arguments, the function deletes the entire string, like member clear.

strIn.erase(strIn.find_last_of('.'));
strIni.erase(strIni.find_last_of('.'));

关于c++ - string::erase 不接受迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9563584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com