1

Below I have two variable store in a char array

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

I try to concat them with stringstream

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

After that I convert it to string

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

Then I try to merge it to form the path of a file and write text in that file

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

ofstream myfile(concat);

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

And I am getting the following error

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

Any idea. Many thanks

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
epiphany
  • 756
  • 1
  • 11
  • 29
  • I can't reproduce your problem on g++: http://coliru.stacked-crooked.com/a/5258e846a9d78fb3. What compiler are you using, and could it be out of date? – alter_igel Apr 11 '19 at 03:51
  • Microsoft Visual c++ 6.0 – epiphany Apr 11 '19 at 03:53
  • Surely the compiler at least says which line the error is on. I suspect it's `ofstream myfile(concat);` and that the char arrays are irrelevant. – chris Apr 11 '19 at 03:59
  • yes, that is right, any solution to this – epiphany Apr 11 '19 at 04:00
  • You don't need the string stream of the temporary `stringh` variable. Just do `std::string filename = start + one + two + end;` – Some programmer dude Apr 11 '19 at 04:03
  • still has this error C2664: '__thiscall std::basic_ofstream >::std::basic_ofstream >(const char *,int)' : cannot convert parameter 1 from 'class std::ba sic_string,class std::allocator >' to 'const char *' – epiphany Apr 11 '19 at 04:06

2 Answers2

3

The problem is that you use a very old version of Visual Studio. Much much older than the C++11 standard, which introduced the ability to pass std::string as filenames to file streams.

You must use a C-style string (const char *) as filename when opening files with e.g std::ofstream.

So the solution with your current code is to do

ofstream myfile(concat.c_str());
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Consider checking out this previous answer for string concatenation How to concatenate two strings in C++?

Michael
  • 546
  • 1
  • 7
  • 19