如何在c++ linux中通过在变量中传递文件名来打开文件

how to open file by passing its name in variable in c++ linux

本文关键字:文件名 文件 c++ linux 变量      更新时间:2023-10-16
#include<iostream>
#include<conio.h>
#include<fstream>
#include<string>
#include<string.h>
#include<vector>
using namespace std;
void main()
{
    string read;
    string name;
    vector<string> myvec;
    const char * word;
    ifstream in;
    in.open("w.txt");
    ofstream out;
        getline(in,read);
        word = strtok(&read[0],",");
        while(word != NULL)
        {
            name = word;
            cout<<"Word: "<<word<<endl;
            name = name + ".txt";
            myvec.push_back(name);
            out.open(name);
            cout<<"Name: "<<name<<endl;
            word = strtok(NULL,",");
            out.close();
        }
    in.close();
    system("pause");
}

我遇到的问题是,当我在ubuntu终端运行它时,它抛出一个错误,通常说out.open()将不接受字符串名称。

我必须创建不同的文件,从文件中获取输入。那么有办法解决这个问题吗?

在c++ 03中,ofstream::open()const char*,而不是std::string;见http://www.cplusplus.com/reference/fstream/ofstream/open/。如果你可以使用c++ 11 (gcc -std=c++11),你可以传递一个std::string