【问题标题】:ofstream variable in name名称中的 ofstream 变量
【发布时间】:2016-06-28 21:29:22
【问题描述】:

我正在尝试创建一个 ofstream,然后将数组中的值写入其中。

void Graph::toFile(char* filename)
{
    ofstream outfile(filename.c_str()+"_new.txt");
    for(int i = 0; i < noOfVertices; i++)
        outfile << graphPartition[i] << endl;
    outfile.close();
}

我的主要问题是,我希望将输出文件命名为filename+"new.txt"。但是,我的方法有问题,因为我不断收到错误expression must have class type。

真的很抱歉,如果这个问题是重复的,我还没有找到令人满意的解决方案。

【问题讨论】:

  • 将char* 替换为const std::string&amp;
  • 并将对c_str()的调用移至+运算符首先被调用之后。
  • 我很想将关闭标记为由于排版错误(尝试使用char * 的方法)... @RemyLebeau c_str() 根本不相关,不需要移动,只需要删除即可。
  • 顺便说一句,如果您选择忽略将char * 替换为std::string 的建议并决定将其保留为指针,那么您应该将其替换为const char *。 (因为如果你不这样做,那么toFile("blah") 将无法在任何现代编译器上工作。)

标签: c++ filenames ofstream


【解决方案1】:

您的问题是 filename 不是 std::string 它是一个 c 字符串 (char*)。 C 字符串不是对象,它们没有方法,它们只是指向内存中以零结尾的字符数组的指针。

filename.c_str()
       -^-

如果文件名是 std::string,则使用这种方法的第二个问题是添加两个 C 字符串指针不会连接字符串,它只是对指针进行数学运算,给你一个地址等于filename.c_str()返回的地址加上“_new.txt”的地址

如果您更改代码以接收文件名作为 std::string

void Graph::toFile(std::string filename)

那么您可以执行以下操作:

filename += "_new.txt";

如下:

void Graph::toFile(std::string filename)
{
    filename += "_new.txt";
    ofstream outfile(filename.c_str());

或

void Graph::toFile(std::string filename)
{
    ofstream outfile(filename + "_new.txt");

演示:

#include <iostream>
#include <string>


void Graph_toFile(std::string filename)
{
    filename += "_new.txt";
    std::cout << "opening " << filename << "\n";
}

int main() {
    Graph_toFile("hello_world");

    return 0;
}

http://ideone.com/eAnfZQ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多