如何连接路径和改变文件名 - C ++

时间:2016-02-02 09:03:51

标签: c++ concatenation

这是我的代码:

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();    

我是C ++的新手。我有一个包含不同文件名的文件夹。我想在for循环中执行一些处理,并将结果保存在具有确切文件名作为输入文件的文件夹中。我该怎么做?请帮忙!

1 个答案:

答案 0 :(得分:3)

连接字符串。使用std :: string而不是char *。 像:

#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;
}

这将在名为test.txt的文件中写入“path / file.txt”。