Posted on 2014-07-12 15:55
eryar 閱讀(3781)
評論(3) 編輯 收藏 引用 所屬分類:
6.Others
今天在輸出數(shù)據(jù)到文件時,用到C++的std::ofstream,結(jié)果文件就是沒有輸出成功,示例程序如下所示:
#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;
}
最后才發(fā)現(xiàn)是文件名有問題,修改程序,去掉生成文件名的一個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;
}
不經(jīng)意間就會寫出這種小錯誤的代碼,而且找錯很很費時。