【发布时间】:2015-04-27 19:18:16
【问题描述】:
作为 C++ 的新手,我看过C++ concatenate string and 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 连接通常有效,但在我希望它是文件名时无效。
所以基本上,我希望文件名是字符串和整数的组合。这对我不起作用,我收到错误
'std::string {aka 中的参数 1 没有已知的转换 std::basic_string}' 到 'const char*'
我希望在 for 循环中使用此逻辑
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 个文件.
【问题讨论】:
-
也许可以尝试更多类似 C++ 的方式将 int 转换为 string(std::to_string)
-
制作一个minimal测试用例。如果您打扰过,您会知道这与连接没有任何关系。您只是没有将正确的参数传递给流构造函数。
标签: c++ string loops concatenation