【问题标题】:C++ int to string, concatenate strings [duplicate]C ++ int到字符串,连接字符串[重复]
【发布时间】:2013-09-14 14:45:05
【问题描述】:

我是 C++ 新手,正在从事一个简单的项目。基本上我遇到问题的地方是创建一个文件名中带有数字(int)的文件。如我所见,我必须首先将 int 转换为字符串(或 char 数组),然后将这个新字符串与文件名的其余部分连接起来。

这是我目前无法编译的代码:

int n; //int to include in filename
char buffer [33];
itoa(n, buffer, 10);
string nStr = string(buffer);

ofstream resultsFile;
resultsFile.open(string("File - ") + nStr + string(".txt"));

这会产生一些编译错误(在 Linux 中编译):

  1. itoa 未在此范围内声明
  2. 没有匹配函数调用“std::basic_ofstream char, std::char_traits char ::open(std::basic_string char, std::char_traits char , std::allocator char)”

我已经尝试过这里的建议:c string and int concatenation 在这里:Easiest way to convert int to string in C++ 没有运气。

如果我使用 to_string 方法,我会得到错误“to_string not a member of std”。

【问题讨论】:

  • 如果你买得起 C++11,一个更简单的将整数转换为字符串的方法是使用std::to_string。例如,请参阅我的答案。

标签: c++ string g++


【解决方案1】:

您可以使用stringstream 来构造文件名。

std::ostringstream filename;
filename << "File - " << n << ".txt";
resultsFile.open(filename.str().c_str());

【讨论】:

  • 这看起来很有希望。但是,当我编译代码时,出现错误:“聚合‘std::ostringstream 文件名’类型不完整,无法定义”
  • 我不认识那个错误。你需要在源文件的顶部#include &lt;sstream&gt;
【解决方案2】:

对于itoa,您可能缺少#include &lt;stdlib.h&gt;。请注意itoa 是非标准的:将整数格式化为字符串的标准方法为sprintfstd::ostringstream

ofstream.open() 采用 const char*,而不是 std::string。使用.c_str()方法从后者获取前者。

把它放在一起,你正在寻找这样的东西:

ostringstream nameStream;
nameStream << "File - " << n << ".txt";
ofstream resultsFile(nameStream.str().c_str());

【讨论】:

    【解决方案3】:

    您想使用boost::lexical_cast。您还需要包含任何需要的标题:

    #include <boost/lexical_cast>
    #include <string>
    std::string nStr = boost::lexical_cast<std::string>(n);
    

    那么简单:

    std::string file_name = "File-" + nStr + ".txt";
    

    因为std::strng 可以很好地处理字符串文字(例如“.txt”)。

    【讨论】:

    • 或者,如果您没有,请使用字符串流。
    【解决方案4】:

    使用std::ostringstream:

    std::ostringstream os;
    os << "File - "  << nStr << ".txt";
    std::ofstream resultsFile(os.str().c_str());
    

    使用std::to_string (C++11):

    std::string filename = "File - " + std::to_string(nStr) + ".txt";
    std::ofstream resultsFile(filename.c_str());
    

    【讨论】:

      【解决方案5】:

      对于itoa函数

      include <stdlib.h>
      

      考虑这个链接

      http://www.cplusplus.com/reference/cstdlib/itoa/

      【讨论】:

      • #include,不包括。
      【解决方案6】:

      您可以使用std::stringstream

      std::stringstream ss;
      ss << "File - " << n << ".txt";
      

      由于构造函数需要一个 char 指针,因此您需要使用将其转换为 char 指针

      ofstream resultsFile(ss.str().c_str());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-24
        • 2017-01-05
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        • 2016-03-02
        • 1970-01-01
        相关资源
        最近更新 更多