必须有一个简单的方法来做到这一点......
// C# code
for (int i = 0; i < 20; i++)
doSomething(i.ToString() + "_file.bmp");
我正在尝试用C ++做这件事,但事实证明,最简单的事情是用这种语言最难做到的。主要是因为有一个问题:我被限制在一个只接受char*
作为函数参数的库中,这最终会进入,所以我几乎被卡住了char
阵列。这就是我到目前为止所做的:
char* path[12];
for(int i = 0; i < 20; i++)
{
sprintf(path[0],"%i_Card.bmp",i);
cards[i] = new Card(i,path[0]);
}
问题是,这种方法最终导致了一个长而无用的大字符串。
我必须透露这是针对学校作业的,但回答这个问题不会决定我的成绩,只会使应用程序的一个方面更容易。
答案 0 :(得分:6)
与ToString相当的C ++ 03是
std::stringstream stream;
stream << i;
std::string i_as_string = stream.str();
请注意,通过执行( std::stringstream() << i ).str()
,您也可以在没有中间变量的情况下完成此任务。
在C ++ 11中,有两个std::lexical_cast< std::string >( i )
可以为您执行上述操作(也可以从Boost获得)和std::to_string( i )
。
答案 1 :(得分:5)
试试这个
#include <stdio.h>
#include <stdlib.h>
itoa(i)
或者你可以去 this 路线:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
答案 2 :(得分:1)
我在你的代码中看到了几个错误。
1)您将“path”声明为12个字符指针的数组,但没有为任何数组项分配内存。 sprintf语句保证复制到垃圾记录中。我很惊讶这不会立即导致您的程序崩溃。
2)即使为路径数组分配了内存,你的sprintf语句也会复制到路径[0] - 覆盖已存在的内容。
我怀疑你在C / C ++中混淆char数组,字符串和字符串数组。也许下面的代码会有所帮助。我假设你的“Card”类没有将作为第二个参数传递的字符串的副本保存到成员变量(至少没有复制它)。否则,它将指向堆栈内存 - 如果您的Card实例超过创建它的函数,那么这可能是错误的。
const size_t MAX_INTEGER_LENGTH = sizeof(int) * 4; // 4x the sizeof int will suffice no matter what the sizeof(int) is
char szPostfix[] = "_Card.bmp";
for(int i = 0; i < 20; i++)
{
char path[MAX_INTEGER_LENGTH + sizeof(szPostfix) + 1]; //+1 for null terminator
sprintf(path,"%d%s",i, szPostfix);
cards[i] = new Card(i,path);
}
答案 3 :(得分:0)
您可以使用std::string
并使用std::string::c_str()
将其转换为c字符串。但是,它返回一个const char *的c字符串。 const_cast
可用于取消与之相关的常量。
#include <iostream>
#include <string>
using namespace std;
void foo(char* str){
cout << str << endl;
}
int main(){
string str = "Hello World";
foo(const_cast<char*>(str.c_str()));
return 0;
}
输出:Hello World
答案 4 :(得分:0)
在C ++中没有将对象转换为字符串的通用方法。您必须自己定义转换函数。对于基本类型,您可以使用stringstream将它们转换为字符串。
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
stringstream ss;
ss << 1;
cout << ss.str();
}
的更多信息
答案 5 :(得分:0)
从代码看起来它是一个文件名,Card
类应该将路径视为const char*
。所以我认为以下是c ++的做法。
for(int i = 0; i < 20; i++)
{
std::stringstream out;
out << i << "_Card.bmp";
cards[i] = new Card(i,out.str().c_str());
}