2011-05-12 74 views
1

有创建的字符串(STD或(常量)字符*)从字符串(为const char *)和数量(INT)创建的,像创建迭代串

animation0,动画1,animation2更好/更快的方式。 .. animation99

比这个?

注:不必须使用std,因为hasValueForKey接受为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;    
} 

感谢

+0

你已经拥有什么可能是最好,最安全的方式(尽管也许你可以跳过一步,并初始化为“动画”而不是空字符串)。 – leegent 2011-05-12 10:31:34

回答

1

那么你可以使用C99 APIsnprintf(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); 
} 
+0

呃,没有。它是C++,如果你需要printf-like,可以使用Boost.Format。 – 2011-05-12 10:35:23

+0

你可以,但这不会更好... – 2011-05-12 10:35:37

+0

@Cat Plus Plus:那么,C99有什么错?它仍然有效;)另外,Boost是一个外部库,必须下载,编译和维护,'snprintf()'符合C99标准,因此它适用于每个编译器。另外,为什么使用复杂的结构,如果他需要的只是一个char *'? – Constantinius 2011-05-12 10:39:00