Thursday, July 9, 2009

C++ program problem with function?

// This program by Dillon Nicholson gets numbers by the user


// then counts the number of digits in the number either being both


// positive or negitive whole numbers





#include %26lt;fstream%26gt;


#include %26lt;iostream%26gt;


using namespace std;





void countingFunction();





int main()


{


ofstream out;


out.open("output.txt");





int num;





out%26lt;%26lt;"This is the program of : ";


out%26lt;%26lt;"Dillon Nicholson"%26lt;%26lt;"\n";


out%26lt;%26lt;"CMPS 1043-02"%26lt;%26lt;"\n";


out%26lt;%26lt;"Due date:";


out%26lt;%26lt;" Nov 15 2007"%26lt;%26lt;"\n"%26lt;%26lt;"\n";





countingFunction();





out.close();


return 0;


}





void countingFunction()





{





while (num != 0)


if (num %26lt; 0) num*=-1;


count = 1;


else if (num %26gt;= 10)


{count++;


num= num / 10;


out%26gt;%26gt; num;


}

















tell me whats wrong i cant tell but it wont build right says 'num' : unreferenced local variable on line 16 but theres nothing wrong that i see

C++ program problem with function?
you declare your "num" variable outside main()


like:





int num = 0;





int main()


{


ofstream out;


out.open("output.txt");








hope this helps
Reply:I'm pretty sure you're seeing two different errors in your code. One will say "Unreferenced local variable" and be pointing to your "int num;" line. The other will say something to the effect that 'num' is not a valid type or is unknown, and it'll be pointing to your "while(num!=0)" line.





The problem here is because of 'scope'. Scope is basically what a particular part of the code has access to, as far as variables are concerned. What you've done is you've declared your variable 'num' in main, and then you're attempting to use that variable from your countingFunction(). countingFunction() doesnt share scope with main, so it cant see that variable.





You need to move 'num' down to be in countingFunction().





You'll also need to somehow get the "ofstream out" variable to be available in countingFunction(). You can do this in two ways... One is to pass that variable as a parameter to the function, and the other is to make that variable global. To make it global, just move it out of and before the main() function. I'd recommend using a parameter, and passing it by reference, if you know how to do that. :)





Good luck!
Reply:Your function main is returning a value but it isn't defined as returning a value.





No idea about the undefined variable.
Reply:first declare the variables then use it

flower garden

No comments:

Post a Comment