2015-04-27 45 views
-2

作为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尔斯。

+0

也许试试更多类似C++的方式将int转换为字符串(std :: to_string) – Creris

+1

做一个_minimal_测试用例。如果你有困扰,你会知道这与连接没有任何关系。你只是没有将正确的参数传递给流构造函数。 –

回答

4

字符串和int连接一般工作,但不是当我希望它是一个文件名。

它与连接字符串无关。您的编译器不支持C++ 11,这意味着您无法将std::string作为参数传递给std::ofstream::open。您需要一个指向空终止字符串的指针。幸运的是,std::string::c_str()为您提供了:

myfile.open(result.c_str()); 

注意,您可以直接实例流:

myfile(result.c_str()); // opens file 

至于环路版本,请参阅串联整数和字符串处理的众多副本中的一个。

3

您引用的问题与您的字符串连接问题高度相关。我建议使用C++11 solution如果可能的话:

#include <fstream> 
#include <sstream> 

int main() { 
    const std::string name = "John"; 
    std::ofstream myfile; 
    for (int i = 0; i < 100; i += 20) { 
     myfile.open(name + std::to_string(i)); 
     myfile << "The value is:" << i; 
     myfile.close(); 
    } 
} 

还是stringstream solution兼容性:

#include <fstream> 
#include <sstream> 

int main() { 
    const std::string name = "John"; 
    std::ofstream myfile; 
    for (int i = 0; i < 100; i += 20) { 
     std::stringstream ss; 
     ss << name << i; 
     myfile.open(ss.str().c_str()); 
     myfile << "The value is:" << i; 
     myfile.close(); 
    } 
} 

此外,你应该:

  • 消除杂散包括<iostream><stdio.h>
  • 消除using namespace std;,这是一般不好的做法 - 你甚至不需要它。
  • 简化环路
  • 标记前缀const

(您可以组合使用sprintf(numstr, "%s%d", name.c_str(), i)文件名,但这仅仅是非常差的C++代码。)

+0

第一次听说'std :: to_string'! – coyotte508

0

如果我们第一次启动通过查看循环,我们可以选择从1开始而不是从0开始计数,这样您的第一个文件将是name+20,并且我们在i命中101之前停止计数,这样您的最后一个文件将是name+100

我们还需要将.txt添加到字符串中,以便创建文本文件。
如果您不会更改数据(例如名称),则可以将这些参数作为参考或引用传递给函数。然后,我们需要将i转换为字符串,如果您的编译器支持C++ 11,则可以使用std::to_string()。我选择创建一个ostringstream对象,并存储从成员函数.str()返回的字符串。

这是你的循环编辑:

for(int i=1;i != 101;++i) { 
     if(i%20==0) { 
      ostringstream temp;   // use a string stream to convert int... 
      temp << i; 
      str = temp.str();    // ...to str 
      result = name + str + ending; // concatenating strings. 
      myfile.open(result); 
      myfile << "The value is:" << i; 
      myfile.close(); 
     } 
} 

现在是将函数的在这个循环中,所有相关的参数传递给它一个好主意。这是一个完整的工作demo

输出文件:John20.txt,John40.txt,John60.txt,John80.txt,John100.txt
还有其他的方法来做到这一点,但是这应该给你一个大概的概念。希望能帮助到你。