c++ - 变量 'sortArray'周围的堆栈已损坏

标签 c++ arrays memory runtime-error

运行时检查失败#2-变量'sortArray'周围的堆栈已损坏。

我在最后一行得到了该程序,该程序旨在创建一个随机数列表,然后对它们进行排序(WIP)。我认为可能是数组大小小于test.txt中的行数,所以我将其从100增加到101毫无用处。

//#include <cstdlib>
#include <iostream>
#include <fstream>  
#include <ctime>
#include <string>

using namespace std;

int main()
{
    //srand(time(NULL));
    std::ofstream outfile("C:\\Users\\smasher248\\Desktop\\test.txt");
    int randomNumber;
    for (int x = 0; x < 100; x++)
    {
        randomNumber = rand() % 9000 + 1000;
        outfile << randomNumber <<"\n";

    }

    outfile.close();
    std::ifstream infile("C:\\Users\\smasher248\\Desktop\\test.txt");
    std::string lineHolder;
    int lineCounter = 0;
    int sortArray[101];
    while (std::getline(infile, lineHolder))
    {
        sortArray[lineCounter] = stoi(lineHolder);
        cout << sortArray[lineCounter] << "\n";
        lineCounter++;
    }
    infile.close();
    int swapContainer;
    for (int i = 0; i < 101; i++)
    {
        if (sortArray[i] > sortArray[i+1])
        {
            swapContainer = sortArray[i];
            sortArray[i] = sortArray[i + 1];
            sortArray[i + 1] = swapContainer;
        }
        std::ofstream sortedFile("C:\\Users\\smasher248\\Desktop\\test_sorted.txt");

        sortedFile << sortArray[i] << "\n";
    }
}

最佳答案

您只需要对代码进行一些更改。

  • 在代码的开头包括<algorithm>
  • ofstream(...)中,添加..., std::ios::app)以追加到文件中。
  • 要对数组进行排序,请删除ofstream语法上方的整个条件表达式块,并在循环之外添加std::sort(sortArray, sortArray + 100)
  • 在该For循环中,将值101更改为100

  • 这样就完成了。

    关于c++ - 变量 'sortArray'周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62026092/

    相关文章:

    c++ - COM、COM+、DCOM,从哪里开始?

    c++ - 调试 :FASTLINK - What is this error?

    c++ - C++ 中的 while 循环中始终存在变量

    c - 结构体中数组的内存分配

    arrays - nodejs 如何创建多维数组?

    linux - kubectl顶级节点报告的内存利用率高于Linux系统命令

    c - 为线程分配堆栈内存

    c++ - 动态创建自定义对象类型数组

    c# - 如何通过dll从c#获取c数组?

    c++ - 打开文件和关闭文件语句定位: best practice,的优缺点