读书人

文件读取写入的简单有关问题有高分

发布时间: 2013-10-16 11:29:46 作者: rapoo

求助,文件读取写入的简单问题,有高分
各位大侠,有如下问题,

现有一个txt文件,n行1列,如下:
12340001
12340002
12340003
56780001
56780002
67890001
........

要求生成若干个后缀名为.dat的文件,
即1234.dat
5678.dat
6789.dat
1234.dat对应的文件内容为n行1列,有格式要求
"0001",
"0002",
"0003"
------------------
5678.dat对应的文件内容为n行1列,有格式要求
"0001",
"0002"
------------------
6789.dat ......
------------------

请赐予完整的C/C++程序,今晚急用,在线等

引用:
#include <string>
#include <fstream>
#include <cassert>

void foo(std::string const& line)
{
assert(line.size() > 4);
std::ofstream ofs(line.substr(0,4).c_str(), std::ofstream::app);
ofs << "\"" << line.substr(4) << "\"" << std::endl;
}

int main()
{
std::ifstream ifs("input.txt");
std::string line;
while(std::getline(ifs, line))
{
foo(line);
}
}

调试一下。

[解决办法]
引用:
#include <string>
#include <fstream>
#include <cassert>

void foo(std::string const& line)
{
//若输入"abcdxxxxx"
assert(line.size() > 4); //确保每行多于4个字符
std::ofstream ofs(line.substr(0,4) + ".dat", std::ofstream::app); //以追加方式abcd.dat
ofs << "\"" << line.substr(4) << "\"" << std::endl;//输出"xxxxx"到abcd.dat
}

int main()
{
std::ifstream ifs("input.txt");
std::string line;
while(std::getline(ifs, line))
{
foo(line);
}
}


 std::ofstream ofs(line.substr(0,4) + ".dat",  std::ofstream::app); //以追加方式abcd.da

改为

std::string fn = line.substr(0,4) + ".dat";
std::ofstream ofs(fn.c_str(), std::ofstream::app); //以追加方式abcd.da

读书人网 >C语言

热点推荐