现在的位置: 首页 > 综合 > 正文

学习笔记:按行分拆txt文档

2012年06月29日 ⁄ 综合 ⁄ 共 716字 ⁄ 字号 评论关闭

最近在做机器学习方面的东西。用到许多到txt的操作。其中有一个txt按行拆分的代码,留下来做笔记。

输入:combination_test.txt(一共有32行数据)
输出:32个单独的txt文档。名字分别为0.txt  1.txt   2.txt  ... ...

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;
string s[100];  
char data[2560];

void saveText(string fname,string str)
{
    ofstream fout(fname.c_str());
    fout<<str;
}


//读取方式: 逐行读取, 将行读入字符串, 行之间用回车换行区分
//If you want to avoid reading into character arrays, 
//you can use the C++ string getline() function to read lines into strings
void ReadDataFromFileLBLIntoString()
{
     ifstream fin("combination_test.txt");  
     int i=0;
     char a[25];
     string str0=".txt";
    while(getline(fin,s[i]) )
    {    
    itoa(i,a,10);
    string str=a+str0;
    saveText(str,s[i]);
    i++; 
    }
}

int main()
{
   ReadDataFromFileLBLIntoString(); //逐词读入字符串
   system("pause");
   return 0;
}

抱歉!评论已关闭.