Tuesday, July 14, 2009

What could I do to copy a string into a multiple array string in c++?

I am writing a program in c++, I would like to copy a srting into a multiple array string. i have used the srtcpy() function but Iam getting an error message telling me that :


-invalid conversion from 'char' to 'char*'


-initializing argument 1 of 'char*' strcpy(char*, const char*).








//this is what I get as message. and here is my program:


# include%26lt;iostream%26gt;


#include%26lt;string%26gt;


using namespace std;


int main()


{int namsize;


char names[20][20], newname[18] ;


cout%26lt;%26lt;"what is the size of your name";


cin%26gt;%26gt;namsize;


cout%26lt;%26lt;" please enter the name";


cin.getline(newname,namsize);


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


strcpy(names[i][1],newname[i]);


system("pause");


return 0;


}


please could you help me to solve this problem? thanks

What could I do to copy a string into a multiple array string in c++?
do strcpy(names[i],newname) instead of


strcpy(names[i][1],newname[i])


and the for loop should go from 0 to 19.





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


strcpy(names[i],newname);








( i am assuming you want to create 20 copies of the same name in the array)


strcpy has the loop built into it. you just need to pass the pointer to the char array to it ,terminated by null of course.(If u din get the last part, its ok)
Reply:this is a syntax error! you need spaces between char names [20] [20]..that should work!
Reply:/*


just do copy of one string onto the next


eg. shown below is a c++ code


*/


# include%26lt;iostream%26gt;


#include%26lt;string%26gt;


using namespace std;





int main()


{





int namsize;





string names="fanda", newname ;


newname=names;





cout %26lt;%26lt;"\nnames: "%26lt;%26lt;names;


cout%26lt;%26lt;"\nnewname: "%26lt;%26lt;newname;


cout%26lt;%26lt;endl;





system("pause");


return 0;


}
Reply:You are using C++. Seriously consider using std::vector and std::string. Then you don't have to ask really odd questions like "what is the size of your name".





Also consider joining a YahooGroup for C/C++ programming instead of using Yahoo Answers for questions like this. You'll learn a LOT more that way by being part of a community who shares the same interests and goals.


No comments:

Post a Comment