Posted on 2014-07-12 15:55 
eryar 阅读(3812) 
评论(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;
" << 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;
" << 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;
}
不经意间就会写出这种小错误的代码,而且找错很很费时。