c++ - 如何将排序后的数组保存在文本文件中?

标签 c++

我有一个排序数组的程序,我如何保存在文本文件中? 例如:排序后的数组为:1、2、3、4、5。 我怎样才能保存在名为.排序的元素”。 我尝试了很多方法,但排序后的数组不会保存在文本文件中。 我是新手,所以我觉得很难。

这是我的代码。

#include <iostream>
using namespace std;

int main() {
    cout << "Enter number of element:";
    int n; cin >> n;
    int a[n];
    for(int i=0;i<n;i++)
    {
        cout << "element number " << (i+1) << " : ";
        cin >> a[i];
    }
    int e=1, d=3;
    int i, j, k, m, digit, row, col;
    int length = sizeof(a)/sizeof(int);
    int bmat[length][10];
    int c[10];
    for(m=1;m<=d;m++)
    {
        for(i=0;i<10;i++)
        {
            c[i]=-1;
        }
        for(i=0;i<length;i++)
        {
            digit=(a[i]/e)%10;
            c[digit]++;
            row=c[digit];
            col=digit;
            bmat[row][col]=a[i];
        }
        k=-1;
        for(i=0;i<10;i++)
        {
            if(c[i]!=-1)
            {
                for(j=0;j<=c[i];j++)
                {
                k++;
                a[k]=bmat[j][i]; 
                }
            }
        }
        e=e*10;
    }

    cout << endl;
    cout << "Sorted array:" << endl;
    for(int i=0;i<n;i++)
    {
        cout << a[i] << " , ";
    }
    cout << endl;
    system("pause");
    return 0;
}

最佳答案

//Use this code 

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;



int main()
{

    int n = 0; 
    cout << "Enter number of element:";
    cin >> n;

    //Data Structure
    std::vector<int> list;
    //push back element in vector
    for(register int i=0;i<n;++i)
        list.push_back(rand()%10 + 1);

    //do shuffling before sorting because rand() generates increasing order number
    std::random_shuffle(list.begin(),list.end());

    std::sort(list.begin(),list.end());

    ofstream textfile;
    textfile.open ("E:\\example.txt");
    for(size_t i= 0;i<list.size();++i)
        textfile << list[i] <<" ";

    textfile.close();
}

关于c++ - 如何将排序后的数组保存在文本文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27963779/

相关文章:

c++ - 不用 goto 重构代码

c++ - Cassandra C/C++ API cass_statement_bind_timestamp

c++ - 如何将 C++ range-v3 输出到 ostringstream?

c++ - 未在 IHTMLElement 事件处理程序中获取事件参数

c++ - vector 下标超出范围(但不是真的)

c++ - 为什么 gprof 告诉我从 main() 只调用一次的函数被调用了 102 次?

c++ - 如何终止 C++11 中的线程?

c++ - 在将它们写入文件之前比较使用 fprintf 生成的两个结果行

c++ - 我收到 'Invalid Type Int[Int]...' ,但它没有任何意义

c++ - 传递一个自由函数来调用?