Friday, July 31, 2009

Help on c++ code?

basically asked to create a random character (a-z). user input. and check answer. this is my 1st semester of c++. thank you





char letter ();


char* QUESTION(int);


char* answer(int);


void checkanswer(char, char, int);





int main()


{


srand((unsigned) time(NULL));


int level = 10;


char *output = QUESTION (level);


for (int j=0;j%26lt;level;j++)


{


cout %26lt;%26lt; output[j];


}


char *input = answer(level);


for (int l=0;l%26lt;level;l++)


cout %26lt;%26lt; input[l];


checkanswer(*output, *input, level);


int z;


cin %26gt;%26gt; z;


return 0;


}





char* QUESTION(int level)


{


int initial=122, final=97;


char *questions;


questions= new char[level];


for (int i=0;i%26lt;level;i++)


{


questions[i]= rand() % (122 - 97 + 1) + 97;


}


return questions;


}





char* answer(int level)


{


char *input;


input=new char[level];


cout %26lt;%26lt; "\ntype in your answer now: ";


cin %26gt;%26gt; input;


return input;


}





void checkanswer(char *output, char *input, int level)


{





if (output==input)


cout %26lt;%26lt; "\nTRUE";


else


cout %26lt;%26lt; "\nFALSE";





}

Help on c++ code?
It's a pretty good effort but you have a couple of problems and some style issues.





(1) Your prototype and definition don't match so it wouldn't compile.





void checkanswer(char, char, int);


void checkanswer(char *output, char *input, int level)





(2) You always have to be aware in C++ of who/what/where is responsible for allocating and deleting memory. You allocate your char array in ANSWERS() and pass back the pointer to main(). That's ok (not great) but you never delete[] it anywhere. In this size program it is a meaningless oversight. In the real world it is a potentially deadly memory leak.





Start to think in terms of contracts - who is responsible for what - and stick to it. As a general rule for what you are trying to do - initialize and array - it is better to allocate and delete the array in the calling function and just pass the array to the function that operates on it.





(3) style - never capitalize your function names like QUESTIONS(). Caps are for constants and preprocessor macros. It's a convention, not a language rule, but you will only confuse and annoy other developers by doing it.





(4) Learn to use const. In main(), for instance, "int level = 10;" should be "const int level 10;" and





char* QUESTION(int level) should be


char* QUESTION(const int level)





(5) In answer() you do "input=new char[level];" but I think you only want a single char. You also don't delete it anywhere. You should rethink this whole function.





There were some other minor things but you'll get the hang of it. Good work.


No comments:

Post a Comment