Jump to content
  • Advertisement
Sign in to follow this  
guyaton

STL string and vector

This topic is 4834 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

i am trying to store a bunch of std::string to a std::vector. when i go to print them out i get runtime errors. my first attempt was this: printf( "\n\nThe vector\tsize=%d\n", g_DirectoryStructure.size() ); for( int i=0; i<g_DirectoryStructure.size(); i++ ) { sprintf( "%s\n", g_DirectoryStructure.c_str() ) ; } my second attemt was this: printf( "\n\nThe vector\tsize=%d\n", g_DirectoryStructure.size() ); for( int i=0; i<g_DirectoryStructure.size(); i++ ) { string str = g_DirectoryStructure; sprintf( "%s\n", str.c_str() ) ; } **note that str is loaded with the proper string string i do not want to pop them yet, i just want to see what is in them. I add the strings like this: g_DirectoryStructure.push_back( FindFileData.cFileName ); thanks in advance, ~guyaton

Share this post


Link to post
Share on other sites
Advertisement
I'm willing to bet your problem is using sprintf() when you meant to use printf(). The way you have things now is trying to write into what is probably readonly memory.

Share this post


Link to post
Share on other sites
Which is, of course, yet another good reason to be using the new-style I/O, as long as you're already being smart enough to make use of string and vector :)

Share this post


Link to post
Share on other sites
To expand on what Zahlman said, using the C++ Standard Library, this becomes:

#include <iterator> //for std::ostream_iterator
#include <algorithm> //for std::copy
#include <iostream> //for std::cout

std::copy(g_DirectoryStructure.begin(), g_DirectoryStructure.end(), std::ostream_iterator<std::string>(std::cout, "\n"));


Share this post


Link to post
Share on other sites
Well... I didn't really want to load *that* much on him all at once :) There certainly are further advantages to using the standard library "algorithms", but you might find this more familiar for now:


#include <iostream>
int count = g_DirectoryStructure.size();
cout << "\n\nThe vector\tsize=" << count << endl; // endl = "end line"
// Note the operator<< is templated, and thus type-safe. No magic format string needed.
for(int i=0; i < count; ++i) {
cout << g_DirectoryStructure << endl; // don't need to convert back to char*
}

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!