Jump to content
  • Advertisement
Sign in to follow this  
Liam78

problem in c/c++ storing a string from an array into another string..

This topic is 4706 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can any1 help me with the following problem in c / c++ i have... I have an array set up as follows: char *animals[] = {"cat","dog","mouse","elephant,"rhino","snake","fish"}; How can i store the string "rhino" in a variable using the following reference to rhino: animals[4][0]; i have tried something like the following, char hold_word[100] = *animals[1][0]; but it does not seem to work? i will get the error message: "invalid initializer" i would want hold_word to hold the value "rhino" if that is possible.

Share this post


Link to post
Share on other sites
Advertisement
If you are using C++, you should really use std::string. Not only are C strings more difficult to use (in most cases), but they are also more prone to buffer overflow attacks when used improperly. If you insist on using C strings, something like this should work (note: It's been a while since I've worked with C strings and this code is untested):

char hold_word[100];
strncpy(hold_word, animals[4], 100);


Also, animals[4][0] is the first character of the string "rhino"('r').

Share this post


Link to post
Share on other sites
If your using C++, you should really be using std::string, char arrays are very error prone.

ie

#include <iostream>
#include <string>
using namespace std;
int main(){
string animals[] = {"cat","dog","mouse","elephant","rhino","snake","fish"};

string holdword = animals[1];;

cout << holdword << endl;
cin.get(); //keeps the window from closing on dev-cpp not really needed
}




in c you need to use strcpy (or better strncpy since it can avoid avoid some nasty errors)

Share this post


Link to post
Share on other sites
thankyou cocalus and roboguy, both the c++ and c examples work, i guess i will try and move onto using the c++ commands when it comes to strings,

cheers guys

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!