【问题标题】:Exit code -1073741510 at bool if statementbool if 语句处的退出代码 -1073741510
【发布时间】:2018-01-18 21:00:55
【问题描述】:

我正在编写一个提示用户输入 .txt 文件的程序,然后将 ifstream 对象和一个整数数组传递给一个函数 - count_letters(ifstream &, int *arrayInts)。

然后该函数从 ifstream 对象中读取每个字符并存储 a-z 中字符的频率(不区分大小写)。每个字符都被传递给一个 bool 函数,该函数检查它是否是非字母字符。为了便于阅读,我注释掉了 alphabetVect 和 checkVect 向量,因为它们很长。

此时我的程序退出执行。即使我可以看到返回为“真”,for 循环也不会执行。打印出 arrayInt 内容的函数结束之前的循环也永远不会执行。

void count_letters(std::ifstream &fileIn, int *arrayInt)
{
    char c;                 // character variable to read from  fileIn
    bool cACReturn;         // charArrayCheck return value
    int aICount = 0;        // count for arrayInt in for loop
    std::vector<char> alphabetVect {// characters 'a' - 'z'};
    while (fileIn.get(ch))
    {
        tempCh = ch;
        cACReturn = charArrayCheck(ch);
        std::cout << "cACReturn = " << cACReturn << std::endl;

        while (1)
        {
            // If ch is an alphabetical character
            if (cACReturn == true)
            {
                for (size_t i = 0; i < alphabetVect.size(); (i + 2))
                {
                    if (ch == alphabetVect[i] || ch == alphabetVect[i + 1])
                    {
                        std::cout << "success" << std::endl;
                        arrayInt[aICount]++;
                    }
                    aICount++;
                }
            }
            else
            {
                std::cout << "false" << std::endl;
            }
        }
    }

    for (int i = 0; i < 26; i++)
    {
        std::cout << "In count_letter letterArray[" << i << "] = " << arrayInt[i] << std::endl;
    }
}

这里是 charArrayCheck 函数:

bool charArrayCheck(char charIn)
{
    std::vector<char> checkVect {// non alphabet characters};

    for (size_t i = 0; i < checkVect.size(); i++)
    {

        if (charIn == checkVect[i])
        {
            std::cout << "false in charArrayCheck" << std::endl;

            return false;
        }

        else
        {
            if (i == (checkVect.size() -1))
            {
                return true;
            }

            else
            {
                continue;
            }
        }
    }
}

感谢所有帮助。

【问题讨论】:

  • 您的 for 循环不在函数中。那甚至不应该编译。
  • 再次检查您的索引。
  • while (1) {...} 你永远不会 break 跳出那个循环。
  • 看起来你在复制代码时丢失了一些东西。 std::vector&lt;char&gt; alphabetVect {// characters 'a' - 'z'}; 无效。
  • 请编辑您的问题以包含minimal reproducible example

标签: c++ arrays vector exit-code


【解决方案1】:

问题可能是这一行:

            for (size_t i = 0; i < alphabetVect.size(); (i + 2))

因为它从不重新分配i,所以这是一个无限循环。 aICount 不断增加,最终arrayInt[aICount]++ 访问数组边界之外。这会导致未定义的行为,并且由于导致的所有内存损坏,您的程序会崩溃。

应该是:

            for (size_t i = 0; i < alphabetVect.size(); i += 2)

【讨论】:

  • 感谢您的帮助。我是编程新手,我看起来像这样简单的事情
猜你喜欢
  • 2013-11-26
  • 1970-01-01
  • 2015-03-06
  • 2015-12-08
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
相关资源
最近更新 更多