天天看點

學習筆記:按行分拆txt文檔

最近在做機器學習方面的東西。用到許多到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;
}