【问题标题】:Program Crashes when I try to compare two strings in c++?当我尝试在 C++ 中比较两个字符串时程序崩溃?
【发布时间】: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&lt;=runningTotal;吗?不仅仅是t &lt; runningTotal
  • 向我们展示文件加载代码和输入文件的小样本。

标签: c++ string function crash compare


【解决方案1】:

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

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

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

尝试将t&lt;=runningTotal 更改为t &lt; runningTotal 以查看问题是否消失。

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

【讨论】:

  • @Edwin:哈哈,对我来说通常是相反的。
  • 我没有使用向量的原因是我还没有学过它们。我会试试你的建议,看看会发生什么。
  • @user1084680:好的。如果您有时间,take a look at them,它们提供了许多额外的功能,可以为您省去很多麻烦。
  • @AusCBloke 我尝试了你的建议,虽然我的程序没有崩溃,但它只是显示“错误:未找到联系人”。所以有些东西还在,只是不知道是什么...
  • @user1084680:检查输入是否失败并检查输入是什么(调试器)。始终(尤其是在 C/C++ 中)防御性编程(任何事情都可能失败,无论出于何种原因)。
【解决方案2】:

我猜for语句应该是:

for (int t=0; t<runningTotal; t++) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多