2014-11-04 42 views
-1

我有一個文本文件,並希望通過拆分文件中的字符串在兩個文本文件中提取它。C++如何在文本文件中拆分字符串

文本文件是這樣的:

LIST.TXT

A00.0 - Description 
A01 - Some other text here 
B07.2 - Lorem ipsum 
.......................... 

我想提取在一個新的文本文件中的部分「A00.0」,並在另一個文本文件中的描述部分。

Code.txt

A00.0 
A01 
B07.2 

Desc.txt

Description 
Some other text here 
Lorem Ipsum 

誰能幫助我?

+2

打開輸入流和兩個輸出流。從輸入流中讀取一行。拆分輸入行。寫第一個必須流一個,第二個必須流兩個。重複讀取/分割/寫入,直到完成。關於SO的問題和答案已經解決了每一步。 – 2014-11-04 11:43:14

回答

0

你不必真的「分裂」它。

#include<stdlib.h> 
#include<iostream> 
#include<cstring> 
#include<fstream> 
using namespace std; 

int main() 
{ 
    ifstream listfile; 
    listfile.open("List.txt"); 
    ofstream codefile; 
    codefile.open("Code.txt"); 
    ofstream descfile; 
    descfile.open("Desc.txt"); 

    string temp; 
    while(listfile>>temp) 
    { 
     codefile<<temp<<endl; 
     listfile>>temp; 
     getline(listfile, temp); 
     temp=temp.substr(1, temp.length() - 1); 
     descfile<<temp<<endl; 
    } 

    listfile.close(); 
    codefile.close(); 
    descfile.close(); 

    return 0; 
} 
+0

它工作正常,謝謝:) – EBalla 2014-11-04 12:59:53

0

至於這樣做的STL的方式,因爲你提前的分隔符,它的位置知道,你可以如下做到這一點:

std::ifstream file("text.txt"); 
if (!file) 
    return ERROR; // Error handling 

std::string line; 
while (std::getline(file, line)) { 
    std::istringstream iss(line); 
    std::string first, second; 
    iss >> first; 
    iss.ignore(std::numeric_limits<std::streamsize>::max(), '-'); 
    iss >> second; 
    std::cout << first << " * " << second << std::endl; // Do whatever you want 
} 

Live Example

這些步驟中的每一個步驟都可以通過針對「文件打開C++」,「文本分隔符讀取」和類似關鍵字的單個研究來解決。

0
  1. 使用getline()從src文件讀取每一行。 as: while(getline(srcfile,str)) { //todo:: }
  2. 使用find_first_of()拆分這一行字符串。 as: string _token_str = " - "; size_t _pos = str.find_first_of(_token_str); if (std::string::npos!=_pos) { // head: A00.0 string _head = str.substr(0,_pos); // tail: Description string _tail = str.substr(_pos+_token_str.size()); }
  3. 將字符串_head和_tail輸出到您的文件;