eryar

PipeCAD - Plant Piping Design Software.
RvmTranslator - Translate AVEVA RVM to OBJ, glTF, etc.
posts - 603, comments - 590, trackbacks - 0, articles - 0

std::ofstream failed

Posted on 2014-07-12 15:55 eryar 阅读(3687) 评论(3)  编辑 收藏 引用 所属分类: 6.Others

今天在输出数据到文件时,用到C++的std::ofstream,结果文件就是没有输出成功,示例程序如下所示:


#include 
<fstream>
#include 
<sstream>
#include 
<iostream>
#include 
<cassert>

void Output(const std::string &theFileName)
{
    std::ofstream os(theFileName.c_str());

    assert(os.good());

    os 
<< "Just for test" << std::endl;

    os.close();
}

int main(int argc, char* argv[])
{
    std::stringstream ss;

    
// remove the std::endl
    ss << "test" << 1 << ".txt" << std::endl;

    Output(ss.str());

    
return 0;
}

 

最后才发现是文件名有问题,修改程序,去掉生成文件名的一个std::endl即可:

 


#include 
<fstream>
#include 
<sstream>
#include 
<iostream>
#include 
<cassert>

void Output(const std::string &theFileName)
{
    std::ofstream os(theFileName.c_str());

    assert(os.good());

    os 
<< "Just for test" << std::endl;

    os.close();
}

int main(int argc, char* argv[])
{
    std::stringstream ss;

    
// remove the std::endl
    ss << "test" << 1 << ".txt";

    Output(ss.str());

    
return 0;
}


不经意间就会写出这种小错误的代码,而且找错很很费时。

Feedback

# re: std::ofstream failed  回复  更多评论   

2014-07-14 00:36 by pdb.so
多看书,多调试

# re: std::ofstream failed  回复  更多评论   

2014-07-22 17:17 by 云腾
文件名不允许存在特殊字符 www.cppentry.com

# re: std::ofstream failed  回复  更多评论   

2014-07-22 18:38 by eryar
是的。
加上assert()会更好点
@云腾

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理