c++ - 为什么我的字符串失去了它的值(value)?

标签 c++ string compare

出于某种原因,我的 toCheck 变量的值被删除了,我不知道为什么。有什么建议吗?

bool
check(string toCheck){
    printf("toCheck: %s\n", toCheck.c_str());
    ifstream list;
    list.open("list.txt");
    string temp;
    while(list){
        getline(list,temp);
        printf("toCheck: '%s' temp: '%s'\n",toCheck.c_str(), temp.c_str());
        if(temp == toCheck){
            printf("Username exists\n");
            return false;
        }
    }
    printf("returning true\n");
    return true;
}

这是它被传递的内容:TestTrevor

这是输出:

toCheck: TestTrevor  
toCheck: '' temp: 'Trevor'  
toCheck: '' temp: ''  

Username exists

最佳答案

来自您的评论:

It's really hard to debug (which is why I'm using printf) because I'm forking and using processes (this is a server for a VoIP project I'm working on) and the gdb wasn't working when I tried to follow the child process.

强调我的。

如果为 toCheck 动态分配的内存从未真正进入 fork 进程,或者进入但以某种方式被丢弃/覆盖,我不会感到惊讶。

NEW INFO: if I comment out the getLine(list, temp); then it doesn't erase toCheck, any thoughts?

这是您程序中第一次需要 std::allocator 来实际分配内存。


STL 的开发从未考虑过 fork ,因此完全有可能在这个用例中不起作用

您可以使用调试器检查发生了什么。查看为 toCheck 分配内存的地址以及为 temp 分配内存时会发生什么,但这是深入研究。

因为 gdb 似乎有问题,您可以先尝试转储地址 (printf("%x", &toCheck[0]);)。

关于c++ - 为什么我的字符串失去了它的值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10289590/

相关文章:

C++ Visual Studio 2008,将项目从 64 位移动到 32 位

Rcpp 中的 C++ 内置随机工件

swift - 如何将字符串(例如 "iso-8859-1")转换为对应的 String.Encoding 字符串?

MySQL比较字符串与国家字符

在 C 中比较密码的两个字符字符串

arrays - 如何比较两个数组包含相同的项目或不包含在 groovy 中?

c++ - 使用 QListWidget 的 Qt 命令日志

c++ - 是否有计算在单色背景上绘制的 Sprite 边界矩形的算法?

linux - 两个目录树的差异以创建文件/文件夹级别的补丁(包括二进制文件)

javascript - 在javascript setTimeout中将字符串作为函数运行?