我需要编写一个程序,将文本文件中未知数量的数值数据读入数组,然后使用排序参数对数字进行排序。我已经尝试了几个小时,但我无法让该程序正常工作
void sort(double &, double arr[], int s);
int main()
{
fstream myfile;
int size, i = 0;
const int n = 1000;
double x[n];
//reading data
myfile.open("data.txt");
if (myfile.fail())
{
cout << "Error Opening File" << endl;
exit(1);
}
while (!myfile.eof())
{
myfile >> x[i];
cout << x[i] << endl;
i++;
}
size = i - 1;
cout << size << " number of values in file" << endl;
myfile.close();
i = 0;
while (size > i)
{
cout << x[i] << endl;
i++;
}
//sorting
sort(x[n], x[n], size);
i = 0;
while (size > i)
{
cout << x[i] << endl;
i++;
}
return 0;
}
void sort(double &, double arr[], int s)
{
bool swapped = true;
int j = 0;
int tmp;
while (swapped)
{
swapped = false;
j++;
for (int i = 0; i < s - j; i++)
{
if (arr[i] > arr[i + 1])
{
tmp = arr[i];
arr[i] = arr[i + 1];
&[i + 1] = &tmp;
swapped = true;
}
}
}
}
答案 0 :(得分:1)
while (!myfile.eof())
几乎总是错的, Why is iostream::eof inside a loop condition considered wrong? 当你最终阅读文件的结尾。改为使用
while (myfile >> x[i])
在您的情况下,您可以将x
声明为std::vector
,例如
std::vector<double> x;
将内容读入矢量,然后使用
std::sort(x.begin(), x.end());
没有更简单的了。
对于完整的C ++标准库解决方案,您可以使用迭代器和排序算法,例如
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::fstream myfile("data.txt"); // should also test if it's open correctly
std::vector<double> x(std::istream_iterator<double>(myfile), {});
std::sort(x.begin(), x.end());
for(const auto& elem: x)
std::cout << elem << " ";
}
您可以轻松地将上面的代码映射到一个函数。我不知道你的排序参数是什么意思。如果您需要能够对升序/降序进行排序,则可以使用std::less
或std::greater
(需要#include <functional>
)作为std::sort
的第三个参数,例如
std::sort(x.begin(), x.end(), std::greater<double>()); // sorts in descending order
或编写自己的比较器函子/ lambda函数。
答案 1 :(得分:0)
我的C ++生锈了,我没有编译器,如果遇到任何错误,我会更新它。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
static bool sort_function (double p, double q);
int main()
{
fstream myfile;
// opening file
myfile.open("data.txt");
if (myfile.fail())
{
cout << "Error Opening File" << endl;
exit(1);
}
// reading data and storing data
vector<double> x;
double tmp;
while (myfile >> tmp)
{
x.push_back(tmp);
}
myfile.close();
cout << x.size() << " number of values in file" << endl;
// unsorted print data from vector
for (vector<double>::iterator it = x.begin(); it != x.end(); ++i)
{
cout << *it << endl;
}
// sorted print data from vector
sort(x.begin(), x.end(), sort_function);
for (vector<double>::iterator it = x.begin(); it != x.end(); ++i)
{
cout << *it << endl;
}
return 0;
}
static bool sort_function (double p, double q)
{
return p > q;
}
您的代码存在一些差异。
std::vector
而不是数组。它是动态的,具有一些令人愉快的功能,如动态长度,大小计数器和排序。那它做什么
data.txt
,如果失败,则会存在。tmp
中,然后将其推送到我们的向量x
中。然后它继续关闭文件并打印值x.size()
的数量。std::sort(begin, end, function)
对矢量进行排序。