【问题标题】:how to open file by passing its name in variable in c++ linux [duplicate]如何通过在c ++ linux中的变量中传递文件名来打开文件[重复]
【发布时间】:2016-09-16 15:43:58
【问题描述】:
#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++ linux fstream ifstream ofstream


【解决方案1】:

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

【讨论】:

  • windows和linux都一样吗?
  • 是的,如果您的编译器符合标准(我猜大多数常见的编译器都属于这种情况)。
  • 这段代码在visual studio上运行良好,但在linux终端上却不行
  • 我猜你的 Visual Studio 版本会默认为 C++11,而gcc 通常默认为 C++03(虽然 6.0 及更高版本似乎是default to C++14)。但是,您将无法在 Linux 中使用 conio.h,请参阅 stackoverflow.com/questions/8792317/…
  • 好的,谢谢。我只会传递 const char *.
猜你喜欢
  • 2016-11-09
  • 2018-06-23
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多