在文本文件C++中保存排序元素
我有一个冒泡排序程序,用升序排序数组 如何将排序后的元素保存在文本文件中,并每隔一个数字(例如-1、0、1、2、3、4)加上逗号 文本文件中是已排序的元素-1,0,1,2,3,4在文本文件C++中保存排序元素,c++,sorting,C++,Sorting,我有一个冒泡排序程序,用升序排序数组 如何将排序后的元素保存在文本文件中,并每隔一个数字(例如-1、0、1、2、3、4)加上逗号 文本文件中是已排序的元素-1,0,1,2,3,4 #include<iostream> #include<fstream> using namespace std; int compare (int, int); void sort(int[], const int); int compare(int x, int y){ retur
#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 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:\n\n"<<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);
cout<<endl;
system ("pause");
return 0;
}
不要使用cout,而是使用文件流。以下是完整的代码:
#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:\n\n" << 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;
}
发布所有代码是不必要的。您可以简单地询问如何将int数组保存到文件中,并显示您迄今为止所做的尝试。。。请确定流是一个流是一个流。无论是std::cout还是某些文件流,所有文本流的工作原理都是一样的。
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();
}
writeToFile(tab, quantity);