作为C++的新手,我查看了C++ concatenate string and int,但我的要求并不完全相同。在cpp中连接字符串和int作为文件名
我有一个样本代码,如下:
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
std::string name = "John"; int age = 21;
std::string result;
std::ofstream myfile;
char numstr[21];
sprintf(numstr, "%d", age);
result = name + numstr;
myfile.open(result);
myfile << "HELLO THERE";
myfile.close();
return 0;
}
字符串和INT级联一般的作品,但不是我希望它是一个文件名。
所以基本上,我想要的文件名是字符串和整数的组合。这不是为我工作,我得到的错误
的参数1没有已知的转换,从 '的std :: string {又名 的std :: basic_string的}' 到 '为const char *'
我想在用于循环这样的逻辑在那里
for(i=0;i<100;i++) {
if(i%20==0) {
result = name + i;
myfile.open(result);
myfile << "The value is:" << i;
myfile.close(); }
}
所以,基本上,每20次迭代,我需要这个“值”要在其中将有名字John20一个新的文件打印, John40等等。所以,对于100次迭代,我应该有5个f尔斯。
也许试试更多类似C++的方式将int转换为字符串(std :: to_string) – Creris
做一个_minimal_测试用例。如果你有困扰,你会知道这与连接没有任何关系。你只是没有将正确的参数传递给流构造函数。 –