Saturday, May 22, 2010

C++ coding problem?

we're learning functions in my C++ class, he's given us function main, we're to write sub-functions that'll complete the task libraries are just iostream. I need to return a value to be stored in the variable userInput, but i can't think of a way to do that without modifying the function main (which i'm not allowed to do) or adding a global variable(which i'm not allowed to do) I don't need the code, just a hint (sorry yahoo answers removes my spacing before my code)





// function get Input has already been declared





int main (void)


{


int userInput;


char letter grade;


char gradeSign;





cout %26lt;%26lt; "input number between 1 and 100\n (an invalid value terminates the program)\n";





while (getInput (userInput))


{


//unrelavant code that uses the variable userInput


}


}





//function i've written so far


int getInput (int getInputVar)


{


cout %26lt;%26lt; "Numeric grade: ";


cin %26gt;%26gt; getInputVar;


if (cin.fail() || getInputVar %26lt;0 || getInputVar %26gt; 100)


return 0;


else


return getInputVar;

C++ coding problem?
I am not positive what you are trying to do, are you asking how to let the "return getInputVar;" return to userInput? If so, there's a simple way to do it. Remember that you want the return value to return to something (i.e. using a =...). Hopefully that's enough of a hint.
Reply:1) how is the function "getinput()" declared? Is it declared with a return value, or no return value? example: int getinput() return value, getinput() no return value.





2) how is getinputVar declared in the arguments list for getinput() function? is it "int getinputVar" or "int* getinputVar"?





3)userinput is never assigned a value before being passed to the getinput() function (just poor programming practice, unless it is a pointer to userinput).
Reply:Can you access userInput from the getInput function you've wrote? Try adding userInput = getInputVar; just after the else and before the return statement at the end, and see if it lets you compile. The reason the program outputs random numbers for userInput right now is because you've declared the variable but haven't assigned any value to it yet, so the value stored at that spot in memory is just whatever happened to be stored there last time that memory spot was used by some program. This is called a garbage value because it means absolutely nothing to you or your program.
Reply:u can use main function to call that function and return its value in a variable as::








main()


{





var = fun( parameter list );





}





return type fun( parameter list );


{





return( what u want );


}





var and return type of function should be compatible


No comments:

Post a Comment