01/10/2018, 12:36

Thao tác trên tập tin trong C++

Khi dùng đoạn mã này thì khi chạy chương trình: ví dụ 8 phần tử em nhập trong file thì lúc xuất ra màn hình thì báo ra 9 phần tử

/*Bài 3: Viết chương trình đọc n số nguyên từ một tập tin cho trước, sau đó sắp
xếp tăng dần rồi ghi kết quả vào 1 tập tin khác.*/

#include<iostream>
#include<stdlib.h>
#include<fstream>

using namespace std;
void sapXep(int arr[100], int &n)
{
	for (int i = 0; i < n - 1; i++)
	{
		for (int j = i + 1; j < n; j++)
		{
			if (arr[i]>arr[j])
			{
				int temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
			}
		}
	}
}
int main()
{
	ifstream filein;
	filein.open("Input.txt", ios_base::in);
	if (filein.fail() == true)
	{
		cout << "
File Input khong ton tai";
		system("pause");
		return 0;

	}
	int arr[100];
	int i = 0;
	int n = 0;
	while (filein.eof() == false)
	{
		filein >> arr[i];
		i++;
		n++;
	}



	ofstream fileout;
	fileout.open("Output.txt", ios_base::out);
	sapXep(arr, n);
	for (int j = 0; j < n; j++)
	{
		fileout << arr[j]<<"   ";
	}

	fileout.close();
	filein.close();

	cout << "Mang co " << n << " phan tu" << endl;
	system("pause");
	return 0;
}
Bài liên quan
0