Monday, May 24, 2010

I have got a little broblem when i compile this c++ code could u help me?

#include%26lt;iostream.h%26gt;


#include%26lt;stdlib.h%26gt;


#define close


struct data{


char name[30];


int year;


}person [close];


int main()


{


char buffer [30];


int n;


cout%26lt;%26lt;"How many persons do u want to enter?";


cin.getline (buffer,30); close=atoi(buffer);


for (n=1;n%26lt;close;n++)


{


cout%26lt;%26lt;"Enter the name of the person: ";


cin.getline (person[n].name,30);


cout%26lt;%26lt;"How old is "%26lt;%26lt;person[n].name%26lt;%26lt;" ?";


cin.getline (buffer,30);person[n].year=atoi(buffer);


}


cout%26lt;%26lt;"The persons data u entered are as follows:\n";


for (n=1;n%26lt;close;n++)


{


cout%26lt;%26lt;person[n].name%26lt;%26lt;" is "%26lt;%26lt;person[n].year%26lt;%26lt;" year(s) old! \n";


}





return main();


}





i want the output to be like this:


how many persons do u eant to enter?


3


enter the name of the person: ben


how old is ben? 19


enter the name of the person: catherine


how old is catherine? 17


enter the name of the person: sophia


how old is sophia? 22


the persons data u entered are as follows:


ben is 19 years old


catherine is 17 years old


sophia is 22 year

I have got a little broblem when i compile this c++ code could u help me?
change three things


#define close


to


#define close 5





for (n=1;n%26lt;close;n++)


to


for (n=0;n%26lt;close;n++)





and


return main();


to


return 0;





then the program works
Reply:One major flaw that probably causes you error is


#define close


has no value also, it's constant you wont be able to change it


unless





#define close(x) x %26gt; 0 ? x : 0





then in your code you can do something like


close(atoi(buffer))


note: This will work like a function with a return value so you'll have to assign it





If you want user input then don't use a #define close


declare it local or global if you want because when you use #define it'll be constant and won't change
Reply:First, you want to change:


for (n=1;n%26lt;close;n++)


to:


for (n=0;n%26lt;close;n++)


Otherwise, it will ask for one less than what you wanted.





Also, you want to change:


return main();


to:


return true;


Otherwise, it will restart as soon as it finishes. (If you want it to automatically run again after it finishes printing, use a while loop like this:





....


int main()


{


while(true)


{


char buffer [30];


....


cout%26lt;%26lt;person[n].name%26lt;%26lt;" is "%26lt;%26lt;person[n].year%26lt;%26lt;" year(s) old! \n";


}


}


return true;


}





it will give the same result, but this is a much better programming style.


No comments:

Post a Comment