Question
When I put in the following code in Code Blocks, a file called salesSorted.txt is being created; however, it always writes 0 - it never
When I put in the following code in Code Blocks, a file called salesSorted.txt is being created; however, it always writes 0 - it never writes the sorted data from the sales.txt file. What am I doing wrong?
#include
using namespace std;
//Function that reads data from user void getSalesData(double *sales, int n, fstream& fin) { string val;
//Iterating over file data for(int i=0; i //Converting to double (sales data) sales[i] = stod(val); } } //Function that sorts data using Selection sort algorithm void sortData(double *sales, int n) { double temp; int minLoc, i, j; //Iterating over array for(i=0; i //Looping over array to find minimum element for(j=i+1; j //Swapping elements temp = sales[i]; sales[i] = sales[minLoc]; sales[minLoc] = temp; } } //Function that writes data to file void writeToFile(double *sales, int n) { int i; //Opening file in output mode fstream fout("salesSorted.txt", ios::out); //Writing number of records fout << n << " "; //Writing data to file for(i=0; i //Closing file fout.close(); } //Main function int main() { int n; string val; double *sales; //Opening file in read mode fstream fin("sales.txt", ios::in); //Checking file opening status if(fin.fail()) { cout << " Error!!! Opening file... "; return 0; } //Reading number of elements fin >> n; //Allocating memory sales = new double[n]; //Reading data from file getSalesData(sales, n, fin); //Closing file fin.close(); //Sorting data sortData(sales, n); //Writing to file writeToFile(sales, n); cout << " Data has been processed and written to file... "; //De-allocating memory delete sales; cout << " "; return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started