我正在尝试使用冒泡排序对三个文件(I/O)进行排序。为此,我编写了以下代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void bubble_Sort_ascending_order(ll n, ll v[]){
ll i,j;
for(i=1; i<=n-1; i++)
{
for(j=1; j<=n-i; j++)
{
if(v[j]>v[j+1])
swap(v[j],v[j+1]);
}
}
}
int bubble_Sort_ascending_input1() {
freopen("input1.txt","r",stdin);
freopen("output_File1.txt","w",stdout);
ll n;
cin >> n;
ll t[n];
for(ll i=1; i<=n; i++)
{
cin >> t[i];
}
bubble_Sort_ascending_order(n,t);
for(ll k=1; k<=n; k++)
{
cout << t[k] << endl;
}
}
int bubble_Sort_ascending_input2() {
freopen("input2.txt","r",stdin);
freopen("output_File2.txt","w",stdout);
ll n;
cin >> n;
ll r[n];
for(ll i=1; i<=n; i++)
{
cin >> r[i];
}
bubble_Sort_ascending_order(n,r);
for(ll k=1; k<=n; k++)
{
cout << r[k] << endl;
}
}
int bubble_Sort_ascending_input3() {
freopen("input3.txt","r",stdin);
freopen("output_File3.txt","w",stdout);
ll n;
cin >> n;
ll v[n];
for(ll i=1; i<=n; i++)
{
cin >> v[i];
}
bubble_Sort_ascending_order(n,v);
for(ll k=1; k<=n; k++)
{
cout <<v[k]<<endl;
}
}
int main(){
bulble_Sort_ascending_input1();
bubble_Sort_ascending_input2();
bubble_Sort_ascending_input3();
}第一个输入文件函数输出工作正常。第二个和第三个输入函数给出了输出文件二和三中的垃圾值。
但我似乎找不到任何类似问题的解决方案。由于某些原因,我在理解文件I/O方面确实遇到了问题。提前感谢你的帮助。
发布于 2020-12-10 18:57:31
这可能不能回答您的问题,但我在您的bubble sort算法中看到了一些缺陷。首先,您的索引必须从0开始,否则您将永远不会读取数组中的第一个元素,然后您可以通过for循环中的正确条件来提高速度。
然后,您可以将bubble_Sort_ascending_input()方法编写为具有std::string input_file_name和std::string output_file_name等参数的方法。然后,您将更容易地调试程序并查看问题所在。
看在上帝的份上,不要使用#include <bits/stdc++.h>。
#include <fstream>
using namespace std;
typedef long long ll;
void bubble_Sort_ascending_order(ll n, ll v[]) {
ll i,j;
for(i = 0; i < n-1; i++) {
for(j = 0; j < n - i -1; j++) {
if(v[j] > v[j+1])
swap(v[j], v[j+1]);
}
}
}
void bubble_Sort_ascending(const std::string& input_file, const std::string& output_file) {
fstream input("../"+input_file, fstream::in);
fstream output("../"+output_file, fstream::out);
// "../" is just for IDE, if you run it from cmd, delete the path
ll n;
if (input.is_open()) {
input >> n;
ll arr[n];
int i = 0;
while (input >> arr[i]) {
++i;
}
bubble_Sort_ascending_order(n, arr);
if (output.is_open()) {
for (ll& number : arr) {
output << number << " ";
}
}
} else {
cout << "input not open";
}
}
int main() {
bubble_Sort_ascending("input1.txt", "output1.txt");
return 0;
}https://stackoverflow.com/questions/65230715
复制相似问题