如何连接路径和不同的文件名 - C++

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

本文关键字:文件名 C++ 路径 何连接 连接      更新时间:2023-10-16

这是我的代码:

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 循环中执行一些过程,并将结果保存在文件夹中,并将确切的文件名作为输入文件。我该怎么做?请帮忙!

连接字符串。使用 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"。