Reading a File and Manipulating Data

I have an assignment due tomorrow at midnight so I have 24 hours to finish this.

Assignment: First, you should use Notepad (or any other text editor) to create a file ahead of time. The file should have 6 double values on separate lines. These values represent the earnings of a person for each of the first 6 months in a year; thus each double value will have exactly two places to the right of the decimal. Name this file, "earnings.txt", and save it to your desktop.

Your program should open and then read the 6 double values from this file into an array named 'earnings'. Use a 'for' loop to do this. Then use another 'for' loop to display the earnings as they were in the file.

After this, sort the array , and then display the earnings in sorted order.
Finally, compute and display the average of the earnings.

I have had no problem with doing the first part of creating the file, getting the file to be read by my program and listing all the number in a list format.

Example text file:

1012.30
1400.71
1250.78
5000.40
3050.70
2134.88


Example Output (currently):

The earnings from the file are:

1012.30
1400.71
1250.78
5000.40
3050.70
2134.88


I need to figure out this portion:

After sorting the earnings are:

1012.30
1250.78
1400.71
2134.88
3050.70
5000.40

The average earnings for the half year is $2308.29


My MAIN PROBLEM is I cannot figure out how to read each line and store it into an array. I have tried various methods but since I am using a string to read the lines, I always get errors if I try to make it an double.

Heres my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () 
{
	string line;
	ifstream myfile ("C:\\Users\\AFTEREFFECTS\\Desktop\\earnings.txt");
	
	if (myfile.is_open())
	{
		while ( myfile.good() )
		{
			getline (myfile,line);
			cout << line << endl;
		}
		myfile.close();
	}
	else 
	{
		cout << "Unable to open file"; 
	}
	
	return 0;
}




Any help will be greatly appreciated! Thank you!
You could use a stringstream to try to convert the string you read into a double.
I'm not exactly sure how to use stringstream. Could you give me an example?
http://cplusplus.com/articles/D9j2Nwbp/

See if this article helps you out; it details a general case of converting strings to integers (but a double could just as easily be used). Post again if you have any parts you don't understand.
closed account (DEUX92yv)
I wouldn't use strings. If the values are doubles, use doubles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <fstream>
using namespace std;

int main () 
{
	double earnings[6];
	double sum (0.0), average, temp;
	int i = 0;

	ifstream myfile ("earnings.txt");
	
	if (! myfile.is_open())
	{
		cout << "Unable to open file";
		return 1;
	}

	while (myfile.good())	       // Good practice to check with good(), but
	{			       // if you KNOW it will only be 6 values, consider
		myfile >> earnings[i]; // a 1-to-6 for loop with if(myfile.good() inside
		i++;
	}

	/* I assume you may need the earnings array for something else, and make
	   a copy. If you don't need to do anything else, you can use earnings instead
	   of the copy array I create */
	double *copy = earnings;

	// Now to sort - a bubble sort is simple
	for (int j = 5; j >= 0; j--) {
		for (int k = 0; k < j; k++) {
			if (copy[k] > copy[j]) {
				temp = copy[j];
				copy[j] = copy[k];
				copy[k] = temp;
			}
		}
	}

	for (int m = 0; m < 6; m++) {
                cout << earnings[m] << endl;  // Print originals
	}
        for (int n = 0; n < 6; n++) {
                cout << copy[n] << endl;  // Print sorted
        }

	// Computing average
	for (int l = 0; l < 6; l++) {
		sum += earnings[l];
	}
	average = sum / 6;

	cout << endl << average << endl;

	myfile.close();
	
	return 0;
}
Last edited on
Ok trojandestroy I am eternally grateful for your help! However, it would be bad character of me to leave without completely understanding the process.

Zhuge I looked at the link you gave me and I understand the process it describes. However, I would like to know how to apply that to input output. I need to understand where the code for the conversion takes place:


This is the example from the link provided:

1
2
3
string Text = "456";
int Number;
if ( ! (istringstream(Text) >> Number) ) Number = 0;




Again, thank you both for your help!
Last edited on
You already had in your code the getline() call that would read a line into a string. Just use that to populate the string instead of a hard-coded string Text.

@troj: You ought to not simply complete people's homework assignments for them. Though in this case TC actually seems like they are going to learn from what's posted, too many people will simply take your code and turn it in. Essentially, you've helped them cheat on their assignment.
@Zhouge: This is the reason I am still working on the assignment. I am here to actually learn, not just to turn in an assignment. Also I understand now with the getline() call function. I am going to continue to analyze the code that was posted above since I still have to make comments on what each line is actually doing. Thanks for the help buddy!
1
2
3
4
5
6
7
8
9
10
11
12
13
14

for (int j = 5; j >= 0; j--) 
{
      for (int k = 0; k < j; k++) 
      {
	       if (copy[k] > copy[j]) 
              {
				temp = copy[j];
				copy[j] = copy[k];
				copy[k] = temp;
	       }
       }
}


Could someone explain to me in comments next to each line what is going on here? I am a bit confused with all the different variable names.
Ok, I have posted my modified code and I would like someone to explain to me the areas where I have a ?????? in the comments. I have pretty much understood the whole entire process now. I wanted to post all this so I could show that I do understand it and that I am not just looking for the answer. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <fstream>

using namespace std;

int main () 
{
	double earnings[6];	       //double array named earnings with a size of 6 values
	double sum = 0;	//double variable of sum set to 0
	double average;	//double variable of average
	double temp;	//doube variable for ????
	int i = 0;		//int variable used in a for loop to count number of iterations
	
	cout.precision(2);	//sets output of all numbers to have 2 decimal places
	
	ifstream myfile ("C:\\Users\\AFTEREFFECTS\\Desktop\\earnings.txt");			//opens file with data in it
	
	if (! myfile.is_open())	//checks if file is properly opened
	{
		cout << "Unable to open file";		//Displays "Unable to open file" when above value is false
		return 1;					//?????
	}

	cout << "The earnings from the file are:\n " << endl; 	//standard cout line

	for (i = 0; i <= 5; i++)	//for loop to display unaltered data file with i being the line number
	{
		myfile >> earnings[i];	//reads line of text from myfile and puts it into array earnings with i being line number
		cout << fixed << earnings[i] << endl;	//displays the value put into the array earnings
	}
	
	cout << "" << endl;		//just some blank space
	
	for (int j = 5; j >= 0; j--)    //????????
	{
		for (int k = 0; k < j; k++)    //?????????
		{
			if (earnings[k] > earnings[j])   //??????????
			{
				temp = earnings[j];    //???????????
				earnings[j] = earnings[k];     //???????
				earnings[k] = temp;     //?????????
			}
		}
	}
	
	cout << "After sorting the earnings are:\n " << endl;	//standard output line
	for (int m = 0; m < 6; m++) 	//for loop to display the sorted earnings with m acting in place of i up above
	{
		cout << earnings[m] << endl;	    //just displaying output of earnings array sorted
	}

	for (int l = 0; l < 6; l++) 	//for loop to determine average of the sorted earnings array
	{
		sum += earnings[l];	    //function adding all the numbers in earnings array
	}
	average = sum / 6;	    //function defining average variable and computing

	cout << endl << "The average earnings for the half year is: $" << average << endl;	//standard output

	myfile.close();	      //closing file to not be read anymore
	
	return 0;
}
Last edited on
line 21 return 1; finalizes the main function, since you couldn't read the file you don't want to programm to continue;

lines 40-42, swaping earnings[j] and earnings[k]. you need to save one of them in temp first, otherwise you would just overwritte one variable with the other and then you have the same data in both of them and can't swap anymore.

line 38, in the if statement you check if a swap of the elements of earnings is neccessary.

lines 34-37 and rest of this for loop stuff: in the foor loops you use 2 indices to compare each element of earning with the others. your 2nd loop only runs till j, otherwise you would compare parts you already have compared.
example: compare a,b,c: a with b, a with c, b with c. no need to compare b with a or c with b or c with a.
your first for loop starts at 5 and runs to 0, you start at the maximum here since you check for ">" in the if statement and then swap the bigger number to a higher index. this way you make sure that after j=5 and a complete run through all k your highest index is the highest number and does not need to be checked nor changed again. now you decrease j and start looking for the second highest number, and so on.

Last edited on
Awesome! Thanks! Now if I can just figure out the for loop.
added the for loop part ;)

maybe it's a good idea to check the for loops with a debugger, you will see how the array gets sorted step by step
Last edited on
Thank you so much! You rock!
Topic archived. No new replies allowed.