why can't i pass an already declared string through to a structure?
Code:struct personInfo { char theName[21]; int age; }; int main() { int theAge = 28; char aName[] = "John Smith"; personInfo p = {aName,theAge}; return 0; }
why can't i pass an already declared string through to a structure?
Code:struct personInfo { char theName[21]; int age; }; int main() { int theAge = 28; char aName[] = "John Smith"; personInfo p = {aName,theAge}; return 0; }
my initial thought is why use char? I'm looking at the code now...
I should have added (unless you are using the size restriction of a char)...which you are. I just find string easier to work with than char but then again, I'm just a n00b.
Last edited by FoodDude; 09-27-2005 at 02:59 PM.
See this link.
http://www.cplusplus.com/doc/tutorial/tut3-5.html
Code:int main() { int theAge = 28; char aName[] = "John Smith "; personInfo p; p.age = theAge; strcpy (p.theName, aName); //personInfo p = {aName,theAge}; return 0; }
why not?Originally Posted by FoodDude
Because the C++ string class is more intuitive and safer to use. Of course, in this case I don't know if you can use that struct initialization technique with the non-POD string class. That then brings up the question, why not use a constructor?
You are trying to pass address of the string to a char array.
When array name is given it degenerates and gives base address of that array.In this you are trying to pass char pointer to a char and hence error.Code:personInfo p = {aName,theAge};
Solution-Declare a char pointer instead.
or pass the string instead of variable.Code:struct personInfo { char *theName; int age; };
Third way is to let user enter itCode:struct personInfo { char theName[21]; int age; }; int main() { int theAge = 28; char aName[] = "John Smith"; personInfo p = {"John Smith",theAge}; return 0; }
Code:int main() { personal Info p; cin>>p.thename; }