【发布时间】:2011-12-07 01:53:04
【问题描述】:
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) 语句。当我的程序到达这部分代码时,它会崩溃而不会出现任何错误。我尝试直接将两个刺与== 运算符进行比较,但这仍然导致我的程序崩溃......
此外,让这一切变得如此奇怪的是,当我的程序正在使用我试图删除的未存储在文本文件中的联系人运行时调用该函数时,这段代码可以完美运行。
但是,当我关闭我的程序并从文本文件中加载我的联系信息时,我的程序会崩溃......我知道我的程序正在将文件读入正确的字符串数组,因为我有一个打印功能,所以我知道我所有的联系人都被转移到了正确的结构数组中......
关于如何解决此问题的任何想法?任何帮助,将不胜感激!谢谢
更新:我接受了 cmets 中的建议并将我的 for 循环更改为
t<runningTotal;
但是,当我这样做时,我的程序不会崩溃,但它不会比较字符串...
【问题讨论】:
-
可能是因为 t
-
你确定这个
t<=runningTotal;吗?不仅仅是t < runningTotal? -
向我们展示文件加载代码和输入文件的小样本。
标签: c++ string function crash compare