c++ - ofstream 名称中的变量

标签 c++ filenames ofstream

我正在尝试创建一个 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

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

最佳答案

你的问题是 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

关于c++ - ofstream 名称中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086624/

相关文章:

primefaces - Primefaces文件下载损坏的非英语文件名

Python-向文件名添加单词

C++在循环中写入文件

c++ - 什么样的前端/GUI 用于交易应用程序?

python - 使用来自串行端口的字符串数据来操作振镜扫描仪在更高速度下出错

C++——选择一组特征

python - 在 Python 中处理 UTF 文件名

c++ - ofstream:运行索引不起作用

c++ - 将 C++ 流用于 cout 或文本文件

c++ - CMake:包含 vs add_subdirectory:相对头文件路径