Go Back   MacRumors Forums > Apple Systems and Services > Programming > Mac Programming

Reply
 
Thread Tools Search this Thread Display Modes
Old Feb 17, 2010, 06:14 PM   #1
corywoolf
macrumors 65816
 
corywoolf's Avatar
 
Join Date: Jun 2004
Send a message via Skype™ to corywoolf
C++ Read Integers from File, find sum, find average, find Min/Max average

Hi,

I am in a C++ class and am having trouble piecing together a program that does the following:

(C++)
Read 6 Integers from File, find sum, find average, and find Min/Max average.

I borrowed some code from other forums that had similar programs, but obviously it doesn't match my needs specifically.

Here is the assignment:
Quote:
"Part 1.

1. (Use a while-loop) Write a function called AVE with (input) parameter FileName and return a return value that is the number of integers in the file
Open an existing file (file name: a3.txt). You need to use standard ways to check if the file exists. There are a number of integers in this file. Each integer takes one line.
2) Read from the file, one integer at a time
3) Add all into a single integer TOTAL
4) Calculate the average by dividing TOTAL by the number of integers in the file; that results the Average
5) Print out the Average
6) Close the file.
7) Return Count; that is the number of the integers in the input file

Part 2.

Write a function called MAXMIN with (input) parameter FileName and an integer Count, and return a return average of MAX and MIN:

1) Open an existing file FileName. You need to use standard ways to check if the file exists. There are a number of integers in this file. Each integer takes one line.
2) Read from the file, one integer at a time
3) Find the MAX of all integers
4) Find the MIN of all integers
5) Print out MAX
6) Print out MIN
7) Calculate the average of MAX and MIN
8) Print the average
9) Close the file.
10) Return the average in step 7.

In main program, define the file name (FileName) as a3.txt. Call functions AVE and MAXMIN.
The input file a3.txt is read-only. Your program should not change its contents."
Code:
//******************************************************************************************
// This program calculates the sum, average.
// By Cory Woolf
//******************************************************************************************

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
#include <fstream>
#include <stdio.h>

using namespace std;

main ()
{

while (inFile >> num)
{
	
	if (count3 == 0) 
	{
		max = num;
		min = num;
	}
	if (num > max) 
	{
		max = num;
	}
	if (num < min)
	{
		min = num;
	}
	count3++;
	
	
	sum += num;
	totSum += num;
	count1++;
	count2++;
}
	

	
	
	int main()
	{
		float Max, Min, num;
		int i;
		FILE *fi;
		FILE *fo;
		if ((fi = fopen("a3.txt")) == 0)
        {
			printf("error opening file\n");
			return 1;
        }
		
		fscanf(fi, %f, & Max);
		Min = Max;
		
		for (i = 0; i < 8; i ++)
		{
			if (num > Max)
			{
				Max = num;
			}
			if (Temp < Min)
			{
				Min = num;
			}
		}
		fclose(fi);
		if ( (fo=fopen("a3.txt")) == NULL )
		{
			printf("ERROR opening file\n");
			return 1;
		}
		
		cout << "The minimum value found is %f" << Min;
		cout << "The maximum = " << Max;
		fclose(fo);
		return 0;
		
	}
		system ("Pause");
		return 0;
	}
corywoolf is offline   0 Reply With Quote
Old Feb 17, 2010, 06:39 PM   #2
lee1210
macrumors 68040
 
lee1210's Avatar
 
Join Date: Jan 2005
Location: Dallas, TX
You need to say what the code is doing now, and what problems it has compared to the requirements. Also, ditch code you stole/borrowed and start writing from scratch using what you do know. This will be easier than manipulating code you don't have any familiarity with.

We won't do your homework. We will be glad to help if you get started and run into trouble.

-Lee
lee1210 is offline   0 Reply With Quote
Old Feb 17, 2010, 07:00 PM   #3
corywoolf
Thread Starter
macrumors 65816
 
corywoolf's Avatar
 
Join Date: Jun 2004
Send a message via Skype™ to corywoolf
Quote:
Originally Posted by lee1210 View Post
You need to say what the code is doing now, and what problems it has compared to the requirements. Also, ditch code you stole/borrowed and start writing from scratch using what you do know. This will be easier than manipulating code you don't have any familiarity with.

We won't do your homework. We will be glad to help if you get started and run into trouble.

-Lee
Thanks for the quick response. I wasn't intending anyone to complete this assignment for me. I don't understand how to get individual lines of integer numbers in from a text file and assign them variables.
corywoolf is offline   0 Reply With Quote
Old Feb 17, 2010, 07:43 PM   #4
lee1210
macrumors 68040
 
lee1210's Avatar
 
Join Date: Jan 2005
Location: Dallas, TX
You have a few options. You need an ifstream, which has a constructor that takes a filename to do the open for you. You can then use the extraction operator >> or getline. The conversion to an int you should be able to handle. Summing and tracking the line count should also be trivial using += and ++.

-Lee
lee1210 is offline   0 Reply With Quote
Old Feb 17, 2010, 08:46 PM   #5
corywoolf
Thread Starter
macrumors 65816
 
corywoolf's Avatar
 
Join Date: Jun 2004
Send a message via Skype™ to corywoolf
Quote:
Originally Posted by lee1210 View Post
You have a few options. You need an ifstream, which has a constructor that takes a filename to do the open for you. You can then use the extraction operator >> or getline. The conversion to an int you should be able to handle. Summing and tracking the line count should also be trivial using += and ++.

-Lee
Thanks for the tips, this is the code I began creating from scratch before searching for a similar program online. So am I converting a string to an integer, because a char is only one character, correct?

My professor is very hard to understand because of his accent and his TA is reluctant to explain too much. I am just trying to find examples of similar programs to figure out how to create this program. I have been reading through the file input/output chapter in my book and have found mostly examples of inputing names as strings. Thanks again for your help, it's much appreciated.

Code:
//******************************************************************************************
// This program calculates the sum, average.
// By Cory Woolf
//******************************************************************************************

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
#include <fstream>

using namespace std;

int avg; // Average of Variables
int sum; // Sum of variables

int main () 
{
	ifstream inFile;
	inFile.open("a3.txt"); // Open File
			
	
	while (inFile>>i) // Part 1 Read values from file
	{
		 total= int i
		
		int AVE (int line);
		{
			cout << "The values are: " << num; // Display input values from file
			cout << "The sum is: " << num ; // Sum
			avg = 
			cout << "The average is: " << num / 6; // Average
			
		}
		
	float MaxMin (int num) // Part 2
		{
			int max, min;
			float avg;
			max=0;
			min=0;
			
			if (v)
		
		for (int i=0; i<count; i++)		{
			int v;
			int MAX;
			MAX = v;
			
			
			
		inFile.close ();	
		system ("Pause");
		return 0;
	}
corywoolf is offline   0 Reply With Quote
Old Feb 17, 2010, 08:54 PM   #6
lee1210
macrumors 68040
 
lee1210's Avatar
 
Join Date: Jan 2005
Location: Dallas, TX
Getline should get you a "C string" in an array you pass in. You can pass this to atoi to get an int. If you use >> with an int it would get you an int immediately instead of needing to convert explcitly.

-Lee
lee1210 is offline   0 Reply With Quote
Old Feb 17, 2010, 11:26 PM   #7
notjustjay
macrumors 603
 
notjustjay's Avatar
 
Join Date: Sep 2003
Location: Canada, eh?
I would suggest you break this problem into smaller chunks, and work on them one at a time.

Start by writing a program that takes 6 numbers from keyboard input (e.g. "enter value 1:" "enter value 2:", etc.) and calculates the values you need.

You might even want to break that down further: How do you get an average? How do you keep track of a min/max value? Make sure you understand how all that logic works as you are writing this first program.

Hint: there are several ways you can do this. You can read all of the values into memory first, then do all the calculations at the end. Or, you can keep "running totals" of at least some of the things while you are collecting the values. The latter will require fewer variables and sounds like what your prof is probably looking for.

Once you've got that all working, start with a fresh slate and write a program that reads 6 values from a file and does nothing but print them out.

Finally, put the two algorithms together, using the constraints of the assignment (e.g. put them into function calls instead of "main" programs) and you're done!
__________________
.

Last edited by notjustjay; Feb 17, 2010 at 11:31 PM.
notjustjay is offline   0 Reply With Quote
Old Feb 18, 2010, 12:47 AM   #8
lloyddean
macrumors 6502a
 
Join Date: May 2009
Location: Des Moines, WA
C/C++ does not allow for the embedding of functions within functions thus the following in not legal syntax:

Code:
   
int main()
{
    return_type func1()
    {
        return result_type;
    }

    return_type func2()
    {
        return result_type;
    }

    return EXIT_SUCCESS;
}
Instead subroutines need to be defined ouside of functions thus:

Code:
return_type func1(parms p, ...)
{
    return result_type;
}

return_type func2(parms p, ...)
{
    return result_type;
}

int main()
{
    return EXIT_SUCCESS;
}
lloyddean is offline   0 Reply With Quote
Old Feb 18, 2010, 02:41 AM   #9
MorphingDragon
Banned
 
Join Date: Mar 2009
Location: The World Inbetween
Send a message via Skype™ to MorphingDragon
If it helps for you, write the program as pseudocode before doing any sort of coding. I don't know C++ exactly but the point of Pseudocode is to give an initial logic structure.

Get a piece of paper and pen. Or just type it up quickly.

EG:

Declare Variable Min Max Av Sum
Declare Array Integers(6) *I'm storing the Integers as an array

For Loop
i = 1, a = 0, i < 7, i = i++ a = a++
Read File Location 1 into Integers(0)
End Loop

ETC ETC

---

It's better if you write your own code period, Especially when learning a language. It may seem harder but you reap the benefits afterwards.

Last edited by MorphingDragon; Feb 18, 2010 at 03:01 AM.
MorphingDragon is offline   0 Reply With Quote

Reply
MacRumors Forums > Apple Systems and Services > Programming > Mac Programming

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Similar Threads
thread Thread Starter Forum Replies Last Post
Missing 2010 mbp keys. Cannot find replacements. Can someone help me find these keys? phanesheckham MacBook Pro 2 Nov 18, 2013 03:49 PM
All iPads: Anybody find retina text *harder* to read? bjjp2 iPad 8 Nov 13, 2013 03:54 PM
Can't find my iPhone (Find friends, location serv. probs) orr971 iPhone Tips, Help and Troubleshooting 10 Oct 5, 2013 04:57 PM
Find My Iphone cannot find Mac davyvfr iPad Apps 0 Nov 19, 2012 08:26 PM
[Free] Find Suspect: the new "find the differences" game on your iPhone appsgaga iPhone and iPod touch Apps 0 Nov 9, 2012 09:52 AM

Forum Jump

All times are GMT -5. The time now is 06:12 PM.

Mac Rumors | Mac | iPhone | iPhone Game Reviews | iPhone Apps

Mobile Version | Fixed | Fluid | Fluid HD
Copyright 2002-2013, MacRumors.com, LLC