Sanathana
Sanathana

Reputation: 284

How to concatenate path and varying file names - C++

This is my code:

double loglikelihood = 0; 
double loglikelihood1 = 0;
double THRESHOLD = 5;
double c = THRESHOLD + 1; 

std::ofstream llh_file;
std::ofstream myfile;   
const char *path= "path_of_file_to_be_saved";
myfile = ( string(path) + flags.inference_result_file_.c_str() ); 

for (int iter = 0; c > THRESHOLD; ++iter) {     
    std::cout << "Iteration " << iter << " ...\n";  
    loglikelihood = 0; 

    llh_file.open(myfile.c_str() );
    loglikelihood += sampler.LogLikelihood(&document);
    llh_file << "THE LOGLIKELIHOOD FOR ITER " << iter << " " << "IS: " << loglikelihood << "\n";                  
    llh_file.close();    

I am a newbie to C++. I have a folder containing different file names. I want to do some process in the for loop and save the results in the folder with the exact file names as the input files. How do I do it? Please help!

Upvotes: 5

Views: 9787

Answers (1)

Gabrielle de Grimouard
Gabrielle de Grimouard

Reputation: 2005

To concatenate strings. Use std::string instead of char*. like:

#include <string>
#include <iostream>
#include <fstream>
int main() {
    std::string path = "path";
    std::string file = "file.txt";
    std::string myfile = path + "/" + "file.txt";
    std::string fname = "test.txt";
    std::ofstream f(fname);
    f << myfile;
}

this will write "path/file.txt" in the file named test.txt.

Upvotes: 5

Related Questions