#include <iostream> #include <conio.h> #include <fstream> #include <string> using namespace std; void insertion_sort (char list[], int n) { int i, j; char next; for (i=1; i<=n; i++) { next = list[i]; for (j=i-1; j>=0 && next <=list[j]; j--) { list[j+1] = list[j]; list[j] = next; } } } void quicksort(char list[], int left, int right) { int i, j; char pivot; if (left < right) { i = left; j = right + 1; pivot = list[left]; do { do i++; while (list[i] < pivot ); do j--; while (list[j] > pivot ); if (i < j) swap(list[i], list[j]); } while (i < j); swap (list[left], list[j]); quicksort (list, left, j-1); quicksort (list, j+1, right); } } void sort (char list[], int length, int x) { if(length >= x) quicksort (list, 0, length-1); else insertion_sort (list, length); } int main () { string line; int i; char array[100]; ifstream myfile ("example.txt"); if (myfile.is_open()) { cout << "This is content of the text file: \n\n"; while (!myfile.eof()) { getline (myfile, line); cout << line << endl; } } else cout << "Unable to open file. Please ensure you have file named example.txt on your PC"; myfile.read (array, sizeof(array)); sort (array,100,75); cout << "The first 100 characters after sorting: \n"; for (i=0;i<100;i++) cout << array[i] << " "; getch(); return 0; } |
|
|
myfile.close();
and I advise you to format your code. It will be more readable.file.open ("example.txt",ios::in); cout << "This is content of the text file: \n\n"; getline (file, line); cout << line << endl; file.read (array, sizeof(array)); function_sort (array,100,75); cout << "The first 100 characters after sorting: \n"; for (i=0;i<100;i++) cout << array[i] << " "; |
file.open ("example.txt",ios::in); cout << "This is content of the text file: \n\n"; file.read (array, sizeof(array)); function_sort (array,100,75); cout << "The first 100 characters after sorting: \n"; for (i=0;i<100;i++) cout << array[i] << " "; |
for (int i = 0; i < 100; i++)array[i] = 0;
or memset: