2014-11-04 62 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输出到您的文件;