Results 1 to 17 of 17
  1. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Creating and implementing functions (C++).


    Okay, I've tried to understand functions but it's hard. This assignment has me stuck on it. I was able to do most of this without the need of functions, but once I realized I needed to implement functions, I had to change what I was doing and now it's all wrong.

    This is obviously not the whole program, but if I can figure out how the hell I need to work functions, I should have the rest down.

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    //Function Declarations
    
    // -----------------------------------------------------------------------
    // Return the number of values in input file (already open).
    // -----------------------------------------------------------------------
    int InputCount (ifstream &inF);
    
    int InputCount (ifstream &)
    {
    	int valueCount = 0;		//Initialize the value count at 0.
    	while (inF >> value)	
    	{
    		valueCount += 1;	//Increment value count.
    	}
    }
    
    //Main function.
    
    int main()
    {
    
    // ----------------------------------------------------------------------
    //  Declare variables.
    // ----------------------------------------------------------------------
    // FORMAT: <type> <variable>;  // Declaration comment.
    	
    	int valueCount = 0;      //I doubt I had to declare this variable twice but.
    	float value, square;
    	float sum = 0;
    	float sqSum = 0;
    
    //-| ----------------------------------------------------------------------
    //-| 1. Read names of input and output files.
    //-| ----------------------------------------------------------------------
       
    	ifstream inF;
    	ofstream outF;
    
    //-| ----------------------------------------------------------------------
    //-| 2. Open input file. If this fails, terminate the program.
    //-| ----------------------------------------------------------------------
       
    	inF.open("numbersIn.txt");	//Opens input file.
    
    	if(inF.fail())
    	{
    		return 1;				//Terminates program if file is not found.
    	}
    
    //-| ----------------------------------------------------------------------
    //-| 3. Open output file.
    //-| ----------------------------------------------------------------------
    
    	outF.open("numbersOut.txt"); //Opens output file.
    
    //-| ----------------------------------------------------------------------
    //-| 4. Count the number of values in the input file and calculate the sum.
    //-| ----------------------------------------------------------------------
    
    	int InputCount (&inF);
    
    	//Print results
    	cout << valueCount << " VALUES IN FILE" << endl;
    
    	system("pause");
    	return 0;
    } //main

  2. Twitch.TV Streamer Straight Male
    IGN: SageFlip
    Server: Windia
    Level: 20X
    Job: Bishop
    Guild: KoopaForce
    Alliance: KoopaEmpire
    New_York

    Default Re: Creating and implementing functions (C++).


    So, you must have at least 5 functions, each needing the data from the txt file. The method to reading the values via for statements should be the same for each function, with the end result of each function being different.

    So far that's what I got in terms of tips. I'll mull over it some more after some sleep. Or someone could beat me to it lol.

    BTW, what did you have before you had to change it around to add functions?

  3. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    I just had while loops, which worked pretty well. So basically the while loop that's in that first function, just without the function.

    I'd gotten up to trying to get the variance before noticing, so I got pretty far.

  4. Orbital Bee Cannon
    IGN: SaptaZapta
    Server: Kradia
    Level: 225
    Job: Hero
    Guild: Matriarchy
    Alliance: Dominion

    Default Re: Creating and implementing functions (C++).


    In my very first "computer programming" class, 1980 in highschool, the teacher started by saying "Calculate 2+3".
    Several people yelled out "five!"
    The teacher looked at them quizzically and said, "I didn't ask you to tell me what it adds up to."

    The variable "valueCount" is local. You declared it inside the function, which means no other bit of code can see it. This is called "scope", and the rule of thumb is: a variable can only be seen/accessed inside the closest { } pair it's declared in.

    In order to get "valueCount" out to main() so it can print it, you must use the "return" statement when your function is ready to complete.
    So, InputCount will look like this:
    Code:
    int InputCount (ifstream &inF)
    {
    	int valueCount = 0;		//Initialize the value count at 0.
    	while (inF >> value)	
    	{
    		valueCount += 1;	//Increment value count.
    	}
            return valueCount;
    }
    And the output statement in main() will look like this:
    Code:
    	int InputCount (&inF);  This is not needed, the function was already declared above.
    
    	//Print results
    	cout << InputCount(inF) << " VALUES IN FILE" << endl;
    I hope that helps.

  5. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    Ahh, that helps a lot, thanks! I still have another problem, though...

    I've got errors stating that value is an undeclared variable, and I can see why now. But isn't there a way for the program to find it initialized outside of the function or would I have to declare these variables within the function?

    So basically, as an example;

    Code:
    int InputCount (ifstream &inF)
    {
    	int valueCount = 0;		//Initialize the value count at 0.
    	while (inF >> value)	
    	{
    		valueCount += 1;	//Increment value count.
    	}
    	return valueCount;
    }
    
    int main()
    {
    	float value;
    
    -insert rest of code here-
    }
    EDIT: I ask this because the basic format of our program has the variable declaration inside the main function, and it sort of feels like I'll have all of my declarations within my declared functions.
    Last edited by MariettaRC; 2013-09-16 at 12:56 AM. Reason: oops fixed an error there

  6. Twitch.TV Streamer Straight Male
    IGN: SageFlip
    Server: Windia
    Level: 20X
    Job: Bishop
    Guild: KoopaForce
    Alliance: KoopaEmpire
    New_York

    Default Re: Creating and implementing functions (C++).


    You seem fine under the design constraints to declare that variable in a function instead. Just follow through like you did for InputCount.

  7. Default Re: Creating and implementing functions (C++).


    If you want to use a variable that you declared in main in some other function, you'll need to pass that variable. If you need to make changes to the value of that variable and you want those changes to also take place in main, then pass your variable by reference.

    Code:
    int InputCount (ifstream &inF, float &value)
    {
    	int valueCount = 0;		//Initialize the value count at 0.
    	while (inF >> value)	
    	{
    		valueCount += 1;	//Increment value count.
    	}
    	return valueCount;
    }
    
    int main()
    {
    	float value;
    	InputCount(inF, value)
    
    -insert rest of code here-
    }
    Sorry if I screwed up the syntax, but I think its right...
    Last edited by Quickjumper7; 2013-09-16 at 01:13 AM. Reason: Screwed up the syntax.

  8. Orbital Bee Cannon
    IGN: SaptaZapta
    Server: Kradia
    Level: 225
    Job: Hero
    Guild: Matriarchy
    Alliance: Dominion

    Default Re: Creating and implementing functions (C++).


    Functions are like delegating work. The main program is like the big boss telling the underlings "do your thing and give me the final result". The big boss doesn't want to see the underlings' notes or tools, and she definitely doesn't want to look around their desk for the final report. They must hand it to her all nice and clean.

    In other words, it's good that all the variables are declared inside the functions. The main program only needs the functions' return values.
    If it needs to use them more than once, it may store them in a variable of its own, for example:

    Code:
    int main()
    {
          int count;
    
    - open files etc - 
    
          count = InputCount(inF);
          
          cout << "You entered " << count << " numbers" << endl;
    
          for (int i = 0;  i < count; i++)
          - do whatever -
    }
    Last edited by SaptaZapta; 2013-09-16 at 07:32 AM.

  9. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    All right, fair enough. I've tried passing by reference and it just created a whole mess for me, so I just went with declaring within functions. o_e I'll have to devote some time to understanding how to pass by reference.

    Now I've run into another problem.

    Code:
    float SumOfSquares (istream &inF)
    {
    	//Start from the beginning of the file - Rewind.
    	inF.clear();
    	inF.seekg(0L, ios::beg);
    
    	float sqValue = 0;
    	float sqSum = 0;
    	float value;
    
    	while (inF >> value)	
    	{
    		sqValue = value * value;
    		sqSum += sqValue;	//Add sqValue to sqSum
    	}
    	return sqValue;
    }
    This is giving me 36 as an end result (since 6 is the last number and there are 7 values in my test file), meaning that it's acting as if sqSum is always 0, and that's been declared outside of the loop. I'm not sure what I could have done wrong here.

  10. Orbital Bee Cannon
    IGN: SaptaZapta
    Server: Kradia
    Level: 225
    Job: Hero
    Guild: Matriarchy
    Alliance: Dominion

    Default Re: Creating and implementing functions (C++).


    So, your program now compiles and runs, but doesn't do what you expect it to.
    Now is when you start debugging.
    If your development environment has a debugger, use that. Otherwise, add "debug messages" so you can see what it's doing.

    Like so:
    Code:
    float SumOfSquares (istream &inF)
    {
    	//Start from the beginning of the file - Rewind.
    	inF.clear();
    	inF.seekg(0L, ios::beg);
    
    	float sqValue = 0;
    	float sqSum = 0;
    	float value;
    
    	while (inF >> value)	
    	{
                    cout << "Read value: " << value << endl;
    		sqValue = value * value;
    		sqSum += sqValue;	//Add sqValue to sqSum
                    cout << "Its square is " << sqValue << ", so the sum of all squares so far is " << sqSum << endl;
    	}
    	return sqValue;
    }

  11. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    After looking over it forever and seeing why it's calculating correctly but not giving me the right final answer, I noticed I was returning sqValue and not sqSum.

    HAHA I'M SILLY.

    Thanks, this is really helping. ;_;

  12. Orbital Bee Cannon
    IGN: SaptaZapta
    Server: Kradia
    Level: 225
    Job: Hero
    Guild: Matriarchy
    Alliance: Dominion

    Default Re: Creating and implementing functions (C++).


    Ouch. I didn't notice that either.
    Seems you've got the hang of it, though. Have fun.

  13. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    Ahh... not quite. I mean, I do, but now getting the variance is becoming a challenge.

    Can I call a function within a declared function? I've got this down...

    Code:
    float Variance(int numValues, float avg, float squaresSum);
    
    float Variance(ifstream &inF, int numValues, float avg, float squaresSum)
    {
    	//Start from the beginning of the file - Rewind.
    	inF.clear();
    	inF.seekg(0L, ios::beg);
    
    	//Variance = sumofsquares/#values - average*average (when numValues>0);
    	float variance = 0;
    	avg = Sum (inF) / InputCount (inF);
    	variance = SumOfSquares (inF) / InputCount (inF) - avg * avg;
    	return variance;
    }
    And this is within the main function:

    Code:
    //Prints the variance of the values in file.
    cout << "VARIANCE = " << Variance (inF, numValues, avg, squaresSum) << endl;
    The error I get is that numValues, avg and squaresSum are undeclared variables. I tried declaring them within the function but it just gave me the same error and the error lies on the line where I'm trying to print the variance. :(

  14. Orbital Bee Cannon
    IGN: SaptaZapta
    Server: Kradia
    Level: 225
    Job: Hero
    Guild: Matriarchy
    Alliance: Dominion

    Default Re: Creating and implementing functions (C++).


    If you have the line
    cout << "VARIANCE = " << Variance (inF, numValues, avg, squaresSum) << endl;
    in the main program, then the variables need to be declared in the main program.

    I see you have Variance() calculating "avg" by itself (doing Sum()/InputCount()). If that is the case, main() doesn't need to give it the average.
    Conversely, if main() already calls Sum() and InputCount(), then it can store the result in a variable and pass it to Variance(), who won't need to redo the work.

    So, you can have your code either like this:
    Code:
    float Variance(ifstream &inF);
    
    float Variance(ifstream &inF)
    {
    	//Start from the beginning of the file - Rewind.
    	inF.clear();
    	inF.seekg(0L, ios::beg);
    
    	//Variance = sumofsquares/#values - average*average (when numValues>0);
    	float variance = 0;
    	float avg = Sum (inF) / InputCount (inF);
    	variance = SumOfSquares (inF) / InputCount (inF) - avg * avg;
    	return variance;
    }
    
    int main()
    {
       ...
       //Prints the variance of the values in file.
       cout << "VARIANCE = " << Variance (inF) << endl;
    }
    or you could do it this way

    Code:
    float Variance(int numValues, float average, float squaresSum);
    
    float Variance(int numValues, float average, float squaresSum)
    {
         return squaresSum / numValues - average * average;
    }
    
    int main()
    {
       int count;
       float avg;
       float squares;
    
    - open files etc -
       count = InputCount(inF);
       avg = Sum(inF) / count;
       squares = SumOfSquares(inF);
       
       //Prints the variance of the values in file.
       cout << "VARIANCE = " << Variance (count, avg, squares) << endl;
    }
    In the first case, Variance() needs no input (arguments) other than the input file handle. It calls on the other functions to help it do its work, keeping all calculations and intermediate results hidden from the main program.
    In the second case, main() "micromanages" the functions, telling each one what to do when, and as a result, Variance() is a much simpler function - just the formula - but it needs all the relevant numbers handed to it.

  15. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    I agree, the second one is much simpler. Thanks. I pretty much have all of the calculating functions down. I have one more function to work on, and that is to copy the input file's values into an output file, with two values per line... I think I'll be saving that for last, in case I do manage to miraculously solve that.

    Buuut this is getting embarrassing. I just keep running into problems I just really can't solve by myself. Programming is hard. ;__;

    "Required Input/Output Formats:

    Input Prompt: Enter Name of Input File:
    Enter Name of Output File: "

    I'd just noticed this, so I'm wondering how this needs to work. I had a premade file and had the program open that ( inF.open("NameOfFile.txt"); ) before realizing I couldn't just do that; it looks like the program needs to locate the file I want to use in case I was using a different file name.

    Code:
    int main()
    {
    	...
    	ifstream inF;					//Declared input file.
    	ofstream outF;					//Declared output file.
    
    	cout << "Enter Name of Input File: " << inF << endl;
    	cout << "Enter Name of Output File: " << outF << endl; //PRETTY SURE THESE TWO LINES ARE WRONG.
    
    	inF.open(???);					//Opens input file.
    
    	if(inF.fail())					//Checks if the file was opened successfully.
    	{
    		return 1;				//Terminates program if file is not found. MAY NEED TO USE EXIT INSTEAD OF RETURN, UNSURE HOW.
    	}
    
    	outF.open(???);					//Opens output file.
    	...
    }
    On a side-note, I could really use some sleep right now.

  16. Orbital Bee Cannon
    IGN: SaptaZapta
    Server: Kradia
    Level: 225
    Job: Hero
    Guild: Matriarchy
    Alliance: Dominion

    Default Re: Creating and implementing functions (C++).


    The lines you marked as wrong are wrong on two counts.
    - The first is that they mix output and input: you want to display the prompt (output), and read the file name that the user types in (input).
    - The second is that you are trying to input "inF" and "outF" directly. Yet you already know that you open a file by its name in string form. You currently have
    Code:
    inF.open("numbersIn.txt");
    You even have, in your new code, open(???). So, you know you need to use that method.
    What you want to do is replace the constant string by a variable that you get from the user.

    To fix both counts we create code like this:
    Code:
       string inputFileName;
       cout << "Enter input file name: " ;            // Show prompt.  Note no endl, that keeps the cursor on the same line
       cin >> inputFileName;                               // Get file name
       inF.open(inputFileName);                          // Attempt to open a file by that name.  
    
       if (inF.fail())
    // etc etc as before
    
    // same block for outF
    On a side-note, sleep.
    I guarantee that programming is much easier when you're not exhausted.

  17. Spirit of the Arrow Bi Female
    IGN: MariettaRC
    Server: Windia
    Level: 200
    Job: Bowmistress
    Guild: KoopaForce
    Alliance: KoopaEmpire
    Nebraska

    Default Re: Creating and implementing functions (C++).


    ausdgjdy I KNEW THAT. Yeah, I'm far too tired for this. I'll be sleeping as soon as I get back from class. :(

    As for the second, I had something like that in mind but thought it wouldn't have made sense. Turned out I was half-right with it. Thanks again.

  18.  

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •