我有一个作业,其中我必须从一个名为(“random.txt”)的文件中读取输出总数并将该文件动态复制到一个数组中。然后对文件中的值进行排序。
直到第 20 行,我的程序运行良好并输出我的总值以及文件中的所有数字。
第 21 行以后也运行了,但是当我运行它时它没有输出我在第 20 行中的总数,它也没有按顺序显示值。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
int n=0;
double temp;
fin.open("data.txt");
fin>>temp;
while(fin)
{
n++;
fin>>temp;
cout<<temp<<endl;
}
cout<<"Total:"<<n<<endl;
fin.close(); //Program run fine up to here.
fin.open("data.txt");
double *A;
A=new double[n];
for (int i=0;i<n-1;i++)
for (int j=i;j<n;j++)
if (A[i]>A[j])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
for (int i=0;i<n;i++)
{
while(fin)
{
n++;
fin>>A[i];
cout<<"Array:"<<A[i]<<endl;//Program runs up to here as well but
//but now doesn't print out the total I
//had in my program above and just
//prints A[i] and its not even sorted.
}
}
fin.close();
}
我知道我有很多错误,我是 c++ 的新手,所以我仍在努力学习。老实说,我不知道从第 32 行开始我在做什么。我知道我从 24-31 对我的数组进行了排序,但我不知道如何将我的文件读入我的数组或如何格式化它.
最佳答案
您的数组加载位置错误。它应该在排序之前,但在分配之后:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("data.txt");
double temp;
size_t n = 0;
while(fin >> temp)
{
std::cout << temp << ' ';
++n;
}
std::cout << "Total: "<< n << endl;
fin.close();
if (n > 0)
{
fin.open("data.txt");
double *A = new double[n];
for (int i=0; i<n && fin >> A[i]; ++i);
fin.close();
for (int i=0;i<n-1;i++)
{
for (int j=i;j<n;j++)
{
if (A[i]>A[j])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
for (int i=0; i<n; i++)
cout << "Array[" << i << "]: " << A[i] << endl;
delete [] A;
}
}
老实说,有很多更好的方法来做到这一点。使用标准库容器,这整个动物园减少到...
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
int main()
{
std::ifstream fin("data.txt");
std::vector<double> A{
std::istream_iterator<double>(fin),
std::istream_iterator<double>() };
std::sort(std::begin(A), std::end(A));
for (auto x : A)
std::cout << x << '\n';
}
关于c++ - 使用数据文件对动态数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29871773/