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