C++ 名称中的流变量

C++ 名称中的流变量,c++,filenames,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(); } void图形

我试图创建一个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();
}
void图形::toFile(char*filename)
{
流输出文件(filename.c_str()+“_new.txt”);
for(int i=0;ioutfile您的问题是
filename
不是
std::string
它是一个c字符串(
char*
)。c字符串不是对象,它们没有方法,它们只是指向内存中以零结尾的字符数组的指针

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

如果将代码更改为以std::字符串形式接收文件名

void Graph::toFile(std::string filename)
然后您可以执行以下操作:

filename += "_new.txt";
详情如下:

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

演示:

#包括
#包括
无效图形文件(标准::字符串文件名)
{
文件名+=“_new.txt”;

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

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

如果将代码更改为以std::字符串形式接收文件名

void Graph::toFile(std::string filename)
然后您可以执行以下操作:

filename += "_new.txt";
详情如下:

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

演示:

#包括
#包括
无效图形文件(标准::字符串文件名)
{
文件名+=“_new.txt”;

std::不能用
const std::string&
替换
char*
,并在首先调用
+
操作符之后将对
c_str()的调用移动到。我很想标记为由于排版错误而关闭(尝试使用
char*
的方法)…@RemyLebeau the
c_str()
根本不相关,不需要移动,只需要删除它。顺便说一下,如果您选择忽略将
char*
替换为
std::string
的建议,并决定将其保留为指针,那么您应该将其替换为
const char*
(因为如果您不这样做,那么
toFile(“废话”)
在任何现代编译器上都不起作用。)将
char*
替换为
const std::string&
,并将对
c_str()
的调用移动到首先调用
+
操作符之后。我很想标记由于排版错误而关闭(尝试使用
char*
的方法)…@RemyLebeau
c_str()
根本不相关,不需要移动,只需要删除它。顺便说一句,如果您选择忽略将
char*
替换为
std::string
的建议,并决定将其保留为指针,那么您应该将其替换为
const char*
。(因为如果您不这样做,那么
toFile(“blah”)
将无法在任何现代编译器上工作。)