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

how to save the sorted arrays in textfile?

本文关键字:存在 保存 文本 文件 数组 排序      更新时间:2023-10-16

>我有一个对数组进行排序的程序,如何保存在文本文件中?例如:排序后的数组是: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();
}

如果可以将排序后的数组写入 std::cout ,则可以将其写入文件。在C++中,控制台与文件相同。

把它放在main的末尾:

 cout << "Sorted array:" << endl;
 print_array( std::cout, a, n ); // Show the results to the user.
 std::ofstream save( "array.txt" ); // Open a new file (or overwrite).
 print_array( save, a, n ); // Save the results for later.
 system("pause");
 return 0;
}

并将打印代码放在一个新函数中,该函数可以在main之前定义:

void print_array( std::ostream & s, int * a, int n ) {
 for(int i=0;i<n;i++)
 {
  s << a[i] << " , ";
 }
 s << endl;
}
#include<iostream>
#include<fstream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y){
    return(x > y);
}
void swap(int *x, int *y){
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
void display(int array[], int n){
    for (int i = 0; i<n; i++) {
        cout << array[i] << " ";
    }
    cout << endl;
}
void writeToFile(int array[], int n){
    ofstream myfile;
    myfile.open("example.txt");
    for (int i = 0; i<n; i++) {
        myfile << array[i];
        if (i != n - 1){
            myfile << ", ";
        }
    }
    myfile.close();
}
void sort(int table[], const int n) {
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n - 1; j++) {
            if (compare(table[j], table[j + 1]))
                swap(&table[j], &table[j + 1]);
        }
    }
}
int main(){
    int quantity;
    int* tab;
    ofstream outfile;
    cout << "Enter number of element: ";
    cin >> quantity;
    tab = new int[quantity];
    cout << "Element:nn" << endl;
    for (int i = 0; i < quantity; i++){
        int x = i;
        cout << "#" << ++x << ":";
        cin >> tab[i];
    }
    sort(tab, quantity);
    cout << "The Sorted Elements are: ";
    display(tab, quantity);
    writeToFile(tab, quantity);
    cout << endl;
    getchar();
    getchar();
    //system("pause");
    return 0;
}

简而言之,将此块添加到您的代码中:

ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
    myfile << array[i];
    if (i != n - 1){
        myfile << ", ";
    }
}
myfile.close();
你可以使用

C++ fstream 类,因为你想输出,你可以在这里使用 ofstream。您应该将一些"cout"替换为流实例:

在代码的开头声明它:

ofstream ofs("./sorted_elem.txt", ofstream::out);

想要输出时:

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

C++你真的想使用std::vector或其他一些漂亮的容器来存储数字数组。 要将数组写入文件,您需要打开文件并将每个元素单独写入文件(所有未经测试)。

#include <fstream>
int main()
{
  std::ofstream fp("output.txt");
  int data[5]; // todo: fill
  for (unsitned i = 0; i < 5; ++i)
  {
    fp << data[i] << ' ';
  }
}

再读一遍:

#include <fstream>
int main()
{
  std::ifstream fp("output.txt");
  // todo: Determine the size of the array or guess it (don't guess it!)
  unsigned array_size = 5;
  int data[array_size];
  int n = 0;
  while (fp.good() && n < array_size) fp >> data[n++];
}

但是因为我们使用的是C++,所以我们可以使用std::vector

#include <fstream>
#include <vector>
int main()
{
  std::vector<int> me(5); // todo: fill
  std::ofstream fp("output.txt");
  for (size_t i = 0; i < me.size(); ++i) fp << me[i] << ' ';
  // C++11: for (int d : me) fp << d << ' ';
}

#include <fstream>
#include <vector>
int main()
{
  std::ifstream fp("output.txt");
  std::vector<int> data;
  double buf;
  while (fp >> buf) data.push_back(buf);  // no longer need to guess
}

我认为,到目前为止,这里还没有演示复制选项。

请检查此代码。(假设您的向量已准备好使用,我已经跳过了它)。

该示例使用 C 数组和向量。请尽可能在代码中使用后面的内容。但是,对于复制函数,两者都有效:

#include <iostream>     
#include <iterator>    
#include <vector>      
#include <algorithm>    
#include <fstream>     
int main () {
  int a[10]={0,1,2,3,4,5,6,7,8,9};  
  std::vector<int> v; for (int i=0; i<10; ++i)v.push_back(i*10); //0, 10, 20,...
  std::ofstream fs_a( "c:/temp/out_a.txt" );
  //store space separated
  std::copy ( a, a+sizeof(a)/sizeof(a[0]), std::ostream_iterator<int>( fs_a, " ") );
  //store coma-separated, as one-liner  
  std::copy ( v.begin(), v.end() ), std::ostream_iterator<int>( std::ofstream( "c:/temp/out_v.txt" ), ",") );
  return 0;
}
相关文章: