For a problem, essentially I had to read integers from an input file, add them to an integer array, sort the array, and write a table with the number of appearences in the array for each value. Here is my code below. My input file is just 1 line (-3 4 1 1 3 4). My output file only prints the code produced by this line (output << setw(6) << left << "N" << "Count" << endl;) and nothing else. It works if I use cout, but doesnt print anything to the output file.
int main()
{
ifstream input;
input.open("TextFile2.txt");
if (input.fail()) {
cout << "file could not be opened." << endl;
return 0;
}
int arr[50];
int num;
int count = 0;
while (input >> num) {
arr[count] = num;
count += 1;
}
selectionSort(arr, count);
input.close();
ofstream output;
output.open("output.txt");
printData(arr, count, output);
output.close();
}
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
void selectionSort(int arr[], int size) {
for (int i = 0; i < size; i += 1) {
int min_num = arr[i];
int min_indx = i;
for (int j = i; j < size; j += 1) {
if (arr[j] < min_num) {
min_num = arr[j];
min_indx = j;
}
}
swap(arr[i], arr[min_indx]);
}
}
void printData(int arr[], int size, ofstream& output) {
output << setw(6) << left << "N" << "Count" << endl;
int prev = NULL;`
for (int i = 0; i < size; i++) {
int count = 0;
if (arr[i] == prev)
continue;
for (int j = 0; j < size; j++) {
if (arr[i] == arr[j])
count += 1;
}
output << setw(6) << left << arr[i] << count << endl;
prev = arr[i];
}
}`