1

is there a better / faster way to create string (std or (const) char *) created from string (const char *) and number (int), like

animation0, animation1, animation2 ... animation99

than this?

NOTE : doesnt have to use std, because hasValueForKey accepts const char *

std::stringstream strIter("animation0"); 

int i = 0;
while (hasValueForKey(strIter.str().c_str())) {

    // do some stuff

    ++i;
    strIter.str(std::string());
    strIter << "animation" << i;            
}

thanks

1
  • You already have what's probably the nicest, safest way (although perhaps you can skip a step and initialise strIter to "animation" instead of the empty string). Commented May 12, 2011 at 10:31

1 Answer 1

1

well you could use the C99 API with snprintf(char *str, size_t size, const char *format, ...);:

int i = 0;
char str[50];
while (hasValueForKey(str)) {
    // do some stuff
    ++i;
    snprintf(str, 50, "animation%d", i);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Ugh, no. It's C++, if you need printf-like, use Boost.Format.
@Cat Plus Plus: Well, whats wrong with C99? its still working ;) besides, Boost is an external library, that has to be downloaded, compiled and maintained, the snprintf() is in the C99 standard, so its available for every compiler. Also, why using complex structures if all he needs is a char * ?
@Constantinius: Again, it's C++, not C. snprintf probably will be available (though it might be named differently if it's extension), but that's no reason to disregard better options and jump into using it. printf family from C library is not type safe, and char* is ugly. And IMVHO, avoiding Boost is just stupid.
@Cat Plus Plus: I know that there are more "elegant" options than snprintf() but I thought it was more useful to provide a simple and working answer to OPs question rather to critizice his interfaces. Hm.. type safety is a problem with the printf() function family. But since he knows that he supplies a simple integer, in this example nothing bad can happen. Of course, you are right, Boost is in many cases the way to go. But I think that sometimes simpler tools like snprintf() are more elegant.
just added char str[MAX_CHAR] = "animation0"; to your snippet, and its very fine... i wanted to have that more performance tweaked, than to use the slow std methods (yes, doesnt matter that its not type safe, since its usage is pretty clear)...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.