字符串查找函数返回奇数
string.find function returning odd numbers
我正试图找到找到字符的位置。
const char* normalize(std::string path)
{
std::cout << "executed " << path << std::endl;
//"foo//\bar////bar2///../.bar2" -- foo/bar/bar2
std::size_t found;
std::size_t found2;
std::size_t curchar = 0;
std::string final;
std::string buffer;
bool notdone = true;
while (notdone) {
//std::cout << "loop" << std::endl;
//find the current element
// can be / or
found = path.find("/", curchar);
found2 = path.find("\",curchar);
std::cout << found << std::endl;
SDL_Delay(2000);
if (found != std::string::npos && found2 != std::string::npos) {
if (found < found2){
//read from the curchar to the slash
if (curchar-found > 1){
buffer = path.substr(curchar,found-curchar-1);
//add to path
final = final + "/" + buffer;
}
curchar = found+1;
//buffer will be the file/component
}else{
if (curchar-found2 > 1){
buffer = path.substr(curchar,found2-curchar-1);
//add to path
final = final + "/" + buffer;
}
curchar = found2+1;
}
}else if(found != std::string::npos){
//std::cout << "loop2" << found == std::string::npos << std::endl;
//std::cout << "loop2 " << path.substr(curchar, 1) << std::endl;
if (curchar-found > 1){//
buffer = path.substr(curchar,found-curchar-1);
//add to path
final = final + "/" + buffer;
}
curchar = found+1;
}else if(found2 != std::string::npos){
std::cout << "loop3" << std::endl;
if (curchar-found2 > 1){
buffer = path.substr(curchar,found2-curchar-1);
//add to path
final = final + "/" + buffer;
}
curchar = found2+1;
}else{
std::cout << "finishing" << std::endl;
final = final + "/" + path.substr(curchar,path.size()-curchar);
notdone = false;
}
}
return final.c_str();
}
normalize("test/");
这个代码应该打印出"4",但它却打印出了18。它在无限循环中打印出18个。但是,如果我使用std::cout << path.find("/", curchar) << std::endl
,它确实会打印4。一开始我以为它实际上并没有返回std::size_t
,但我检查了一下,它确实返回了。
您的下一行正在创建问题
//find the current element
// can be / or
found = path.find("/", curchar);
我在我的linux终端上运行,GCC被视为下一行,作为上一行注释的延续。
basic.cpp:18:9: warning: multi-line comment [-Wcomment]
// can be / or
^
basic.cpp: In function ‘const char* normalize(std::string)’:
basic.cpp:21:22: warning: ‘found’ may be used uninitialized in this function [-Wmaybe-uninitialized]
std::cout << found << std::endl;
^
现在,由于上面的注释样式,您的下一行(代码)被视为注释。由于发现未初始化,因此它有垃圾值,这使您的逻辑出错,因为它没有进入您重置标志未完成的路径。
然而,GCC或任何其他编译器都应该发出警告(使用未初始化变量),如果我们仔细阅读,我们可能会进行回溯并理解问题。
解决方案是将注释样式更改为
/* // can be / or */
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数