gpt4 book ai didi

c++ - 当我尝试在 C++ 中比较两个字符串时程序崩溃?

转载 作者:行者123 更新时间:2023-11-30 03:04:45 25 4
gpt4 key购买 nike

int removeContact(Contact *newPtr, int runningTotal)
{
//define variables
string remove;
int next;

//prompt user for name they wish to remove
cout << "Enter the name you would like to delete (Last name first): ";
cin.ignore();
getline(cin, remove);

for (int t=0; t<=runningTotal; t++)
{
if (remove.compare(newPtr[t].name) == 0)
{

//calls function moveArrayElements function
moveArrayElements(newPtr, runningTotal, t);

//decrement runningTotal
runningTotal--;

//prompt user contact was found
cout << "Contact was found and deleted!";

next=1;
}

}

if(next!=1)
{
cout<< "ERROR: Contact was not found!";
}

return runningTotal;
}

此函数是一个更大的 c++ 程序的一部分,该程序旨在管理个人联系信息。这个函数假设删除一个联系人。

我遇到的问题是 if (remove.compare(newPtr[t].name) == 0) 语句。当我的程序到达这部分代码时,它将崩溃而不会出现任何错误。我尝试用 == 运算符直接比较这两个字符串,但这仍然导致我的程序崩溃......

此外,让这一切变得如此奇怪的是,当我的程序运行时调用该函数时,这段代码可以完美运行,而我试图删除的联系人未存储在文本文件中。

但是,当我关闭我的程序并从文本文件加载我的联系信息时,我的程序会崩溃...我知道我的程序正在将文件读入正确的字符串数组,因为我有打印功能,所以我知道我所有的联系人都被转移到适当的结构数组中......

关于如何解决这个问题的任何想法?任何帮助,将不胜感激!谢谢

更新:我采纳了评论中的建议并将我的 for 循环更改为

t<runningTotal;

但是,当我这样做时,我的程序不会崩溃,但它不会比较字符串...

最佳答案

如果runningTotal是你的数组的大小,那么有效元素的范围是[0, runningTotal) .在下面的代码中,您将循环到 runningTotal 包含,当没有有效的 Contact 时那里的对象:

for (int t=0; t<=runningTotal; t++)
{
if (remove.compare(newPtr[t].name) == 0)

因此,当您取消引用 newPtr[t] 时, 对于 t = runningTotal然后尝试获取 name元素,您将导致未定义的行为并可能导致崩溃。

尝试更改 t<=runningTotalt < runningTotal看看问题是否消失。

此外,您使用数组而不是 std::vector 是否有原因? ?

关于c++ - 当我尝试在 C++ 中比较两个字符串时程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8409460/

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