【问题标题】:How to concat char array into a string如何将char数组连接成字符串
【发布时间】:2019-04-11 03:45:19
【问题描述】:

下面我有两个变量存储在一个 char 数组中

char one[7]  = "130319";
char two[7] =  "05A501";

我尝试用 stringstream 连接它们

std::ostringstream sz;
sz << one<< two;

然后我将它转换为字符串

std::string stringh = sz.str();

然后我尝试合并它以形成文件的路径 并在该文件中写入文本

std::string start="d:/testingwinnet/json/";
std::string end= ".json";
std::string concat= start+stringh + end;

ofstream myfile(concat);

myfile << "test";
myfile.close();

我收到以下错误

error C2040: 'str' : 'class std::basic_string<char,struct
std::char_traits<char>,class std::allocator<char> >' differs in levels
of indirection from 'char *

任何想法。非常感谢

【问题讨论】:

  • 我无法在 g++ 上重现您的问题:coliru.stacked-crooked.com/a/5258e846a9d78fb3。您使用的是什么编译器,它可能已经过时了吗?
  • Microsoft Visual c++ 6.0
  • 肯定编译器至少会说明错误在哪一行。我怀疑它是 ofstream myfile(concat); 并且 char 数组无关紧要。
  • 是的,没错,任何解决方案
  • 你不需要临时stringh变量的字符串流。就做std::string filename = start + one + two + end;

标签: c++ c++98 visual-studio-6


【解决方案1】:

问题在于您使用的是 非常 旧版本的 Visual Studio。比 C++11 标准老得多,后者引入了将std::string 作为文件名传递给文件流的能力。

在使用 std::ofstream 打开文件时,您必须使用 C 风格的字符串 (const char *) 作为文件名。

所以你当前代码的解决方案是这样做

ofstream myfile(concat.c_str());

【讨论】:

    【解决方案2】:

    考虑查看之前的答案以了解字符串连接How to concatenate two strings in C++?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2021-10-05
      • 2015-10-27
      • 2012-05-18
      • 1970-01-01
      相关资源
      最近更新 更多