1

I have this line of code

    std::ofstream output(p_strFilename.c_str());

where p_strFilename is defined from a function parameter

    foo(const std::string &p_strFilename)

which is saving a bunch of files in the current working directory. However I want to enter a step inside that directory and save the files inside. I tried

    std::ofstream output("folder1\\"+p_strFilename.c_str())

this is giving me

    error: invalid operands of types ‘const char [9]’ and ‘const char*’ to binary ‘operator+’

which I guess is reading the directory as 9 characters instead of as a string.

First question: Is that the right way to input a directory? (double backslash and starting from the CWD not form home directory)

Second question: How can I resolve my compilation error?

j.doe
  • 13
  • 6

2 Answers2

0

I think you need to convert to c_string only after the concatenation:

std::ofstream output(("folder1/"+p_strFilename).c_str())

Hope it helps! :)

Brutus
  • 790
  • 3
  • 10
  • 27
  • @RawN it should if: 1. p_strFilename is of type std::string and 2. output() takes a "const char *" as parameter. Why do you think it will not compile? – Brutus Dec 16 '16 at 14:27
  • @RawN If p_strFilename is of type "const char*", how can it be that p_strFilename.c_str() works? I thought that c_str() was a method of the std::string type... – Brutus Dec 16 '16 at 14:39
  • although this removed my compilation error, what is happening now is that the files are still being save in the cwd with the name "folder1\file1.txt", "folder1\file2.txt", etc.. how can i solve this – j.doe Dec 16 '16 at 14:45
  • +p_strFilename is not of type char* its of type std::string already.. i edited the question – j.doe Dec 16 '16 at 14:48
  • @j.doe could you try with a "slash" instead of a "backslash"? I'll update my answer accordingly. – Brutus Dec 16 '16 at 14:52
  • you don't need .c_str() ofstream constructor accepts string in c++11 – Rama Dec 16 '16 at 15:15
0

Don't use .c_str().

The operator+ don't work with two char*, you must use std::string operator+ to add strings like this.

std::ofstream output("folder1\\"+p_strFilename);

(One of the two strings being concatenated must be a std::string object)

Community
  • 1
  • 1
Rama
  • 3,222
  • 2
  • 11
  • 26
  • @j.doe, don't you use c_str(), this give you a const char*, but you need a std::string to add the literal string "folder1\\" – Rama Dec 16 '16 at 15:01