Quantcast
Channel: C++博客-eryar
Viewing all articles
Browse latest Browse all 519

std::ofstream failed

$
0
0

今天在输出数据到文件时,用到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;
}


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



eryar 2014-07-12 15:55 发表评论

Viewing all articles
Browse latest Browse all 519


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>