无法使用数组和排序插入.data

时间:2015-02-03 20:55:33

标签: c++ arrays

美好的一天

我在导入.dat文件时遇到问题。我需要使用数组函数以升序获取.dat文件中的值。

以下是我目前的情况,我已经检查了this这样的网站寻求帮助,但没有运气。

.dat文件具有以下数字,应按升序排序:

63 2 23 89 150 890 250 12 36 15 70 62 89 21 20 45 56 26 87 63


#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

//swap function
void sortAscending(int type[], int size)
{
    int Max = 0;

    for (int j = Max; j < (size -1); j++)
    {
        for (int i = Max; i < (size -1); i++)
        {
            if (type[i] > type[i+1])
            {
                int temp = type[i];
                type[i] = type[i +1];
                type[i+1] = temp;
            }
        }
    }

    //Display swapped values
    for (int j = Max; j < (size -1); j++)
        cout << type[j] << " ";

    cout << endl;
}

int main()
{
    ifstream in_stream; //Assign to in_stream

    int filename[20]; //array assigned to 20

    in_stream.open("Numbers.dat"); //Open .dat file

    sortAscending(filename, 20); //call function

    //Check if file failed to load
    if (in_stream.fail())
    {
          cout << "Output file opening failed.\n";
          exit(1);
    }

    in_stream >> filename[20]; //write to in_stream

    in_stream.close();

    system("pause");
    return(0);
}

1 个答案:

答案 0 :(得分:-1)

仅打开一个文件不会自动读取并填充您的数组。你在哪里读取.dat文件到数组的值?

  1. 首先读取所有值并填充数组。
  2. 对数组进行排序。
  3. 将数据写回文件。