从txt文件中读取并将已排序的列表写入新的文本文件程序会崩溃

时间:2013-02-25 22:53:09

标签: c++ file runtime-error mergesort

以下是我的课程和代码:

MergeSort.cpp

#include "MergeSort.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdlib.h>

using std::cout;
using std::ifstream;
using std::string;


void MergeSort::mergeIt(int* input, int first, int last)
{
    int mid = (first + last) / 2;
    int i1 = 0;
    int i2 = first;
    int i3 = mid + 1;

    int temp[last-first+1];

    while ( i2 <= mid && i3 <= last )
        if ( input[i2] < input[i3] )
            temp[i1++] = input[i2++];
        else
            temp[i1++] = input[i3++];

    while ( i2 <= mid )
        temp[i1++] = input[i2++];

while ( i3 <= last )
    temp[i1++] = input[i3++];

    for ( int i = first; i <= last; i++ )
        input[i] = temp[i-first];
}

void MergeSort::mergeSortIt(int* input, int first, int last)
{
    if ( first < last )
    {
        int mid = (first + last) / 2;
        mergeSortIt(input, first, mid);
        mergeSortIt(input, mid + 1, last);
        mergeIt(input, first, last);
    }
}

和mymain.cpp:

#include "MergeSort.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::fstream;
using std::ifstream;
using std::ofstream;

int main() {
    string input, output;
    cout << "The name of the input file?";
    cin >> input;
    cout << "The name of the output file?";
    cin >> output;

    int sizeOfArray = 25000000;

    //int inputArray[sizeOfArray];
    int *A = new int[sizeOfArray];

    ifstream myReadFile;
    myReadFile.open(input.c_str());

    if (myReadFile.fail()) {
        cout << "Error reading";
    }


    int k = 0;
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
         myReadFile >> A[k];
        k++;
        }
    }
    myReadFile.close();



    MergeSort m;
    m.mergeSortIt(A,0,sizeOfArray-1);


    ofstream outFile;
    outFile.open(output.c_str());

    if (outFile.fail()) {
        cout << "Error writing";
    }

    for( int i = 0; i < sizeOfArray; i++) {
        outFile << A[i] + "\n";
    }

    outFile.close();

    delete A;

}

它正确构建并运行但在我输入txt文件后,它等待大约45秒然后说:“exe已停止工作”。

0 个答案:

没有答案