How do I insert a textfile of stings, separated by carrige returns into an string array, or an array of pointers. I have been scratching my head over this for a while now and eventually have to turn for help. Here is as far as I have got, although I now know it won't work. ifstream fpi("names.dat"); char *name[5]; if (!fpi) { cout << "Error opening file\n"; exit(0); } for (int i=0; i<5; ++i) { fpi >> *(name+i); } for (int j=0; j<5; ++j) { cout << *(name+j) << endl; } fpi.close(); As you can see, i'm still pretty new to programming. Thanks, Ged. ----------------------------------------- Email provided by http://www.ntlhome.com/
On Fri, Dec 12, 2003 at 08:50:55AM +0000, ged.suse@ntlworld.com wrote:
How do I insert a textfile of stings, separated by carrige returns into an string array, or an array of pointers.
I have been scratching my head over this for a while now and eventually have to turn for help.
Here is as far as I have got, although I now know it won't work.
Try using the getline() method on the instream. Don't forget to allocate space to hold the strings. Victor
ged.suse@ntlworld.com wrote:
How do I insert a textfile of stings, separated by carrige returns into an string array, or an array of pointers.
I would suggest you use the STL container vector<string> to hold the strings. This allows you to manipulate the object as if it were an array without having to worry about pointers, memory allocation and buffer overruns as you would if you were programming in C. You'll need to use #include<vector> to get this. Here's my version. You'll probably need to tweak this a bit to make sure it works. #include<iostream> #include<fstream> #include<vector> int main(){ std::vector<std::string> names; std::ifstream fpi("names.dat"); while( fpi.good() ){ std::string name; std::getline( fpi, name ); names.push_back( name ); } exit(0); } Now you can refer to a string as names[i] where i is an int in [0, names.size()). You can even use tricks like std::copy( names.begin(), names.end(), std::ostream_iterator<std::string>( std::cout, "\n" ) ); to print off the whole list of strings to standard output. The C-style version of this also works: for( int i = 0; i < names.size(); ++i ) std::cout << names[i] << std::endl; Vectors and strings are a little less efficient than arrays of char*, but IMHO, for most IO it's better to have simple robust code than efficient code that's difficult to check for runtime bugs. -- JDL Non enim propter gloriam, diuicias aut honores pugnamus set propter libertatem solummodo quam Nemo bonus nisi simul cum vita amittit.
participants (3)
-
ged.suse@ntlworld.com
-
John Lamb
-
Victor R. Cardona