C++ 从文件中读取任意数字并对其进行气泡排序
我正试图编写一个程序,从一个文本文件(2112421-5630)中读取一个数组中的数字,并按降序对它们进行气泡排序,然后只打印出正数。我已经尝试了一段时间,但所展示的并不是我所期望的 文本文件的内容包括:C++ 从文件中读取任意数字并对其进行气泡排序,c++,bubble-sort,C++,Bubble Sort,我正试图编写一个程序,从一个文本文件(2112421-5630)中读取一个数组中的数字,并按降序对它们进行气泡排序,然后只打印出正数。我已经尝试了一段时间,但所展示的并不是我所期望的 文本文件的内容包括: 21 12 44 21 -5 63 0 完整代码: #include "stdafx.h" #include <iostream> #include <fstream> #include <iomanip> #include <conio.h>
21 12 44 21 -5 63 0
完整代码:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
class bubble
{
public:
unsigned* arr;
int n;
//Constructor
bubble(const int& size) : n(size) { this->arr = new unsigned[n]; }
//function to read from file
void inputvf(istream &f)
{
//check if file is open
if (f.fail()) {
cout << "\n Error in openning file!!!";
exit(1);
}
for (int i = 0; i < n; i++)
f >> arr[i];
delete[] arr;
//close file
//f.close();
}
//Bubble sort function
void bubblesort()
{
for (int i = 1; i<n; i++)//for n-1 passes
{
for (int j = 0; j<n - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display()
{
cout << endl;
cout << "----------------------\n";
cout << "Sorted array elements \n";
cout << "----------------------\n";
if (arr >= 0){
for (int j = 0; j < n; j++)
cout << arr[j] << endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
bubble list(7);
ifstream file("Text.txt");
list.inputvf(file);
list.bubblesort();
list.display();
_getch();
return 0;
我做错了什么???请帮忙
这是新代码(如下所示):
#包括“stdafx.h”
#包括
#包括
#包括
#包括
使用名称空间std;
阶级泡沫
{
公众:
//保存值的整数数组
int*arr;
//数组中的元素数
int n;
//建造师
气泡(const int&size):n(size){this->arr=new int[n];}
//从文件中读取的函数
无效输入vf(istream&f)
{
//检查文件是否打开
if(f.fail()){
cout>arr[i];
//删除[]arr;
//关闭文件
//f、 close();
}
//气泡排序函数
void bubblesort()
{
对于(int i=1;i两个问题:
在输入vf
中:
delete[] arr;
此时不应删除该数组-您甚至还没有开始使用它
本声明:
unsigned* arr;
这意味着您的所有输入都是无符号的,这意味着-1被读取为4294967291,因此将被视为一个大数字。将数组更改为正常整数,然后在输出时使用if测试忽略负数。谢谢,我尝试了您编写的内容,但仍然是错误的,现在它只是一个大负数。
delete[] arr;
unsigned* arr;