【问题标题】:C++ how to split strings in a text file [duplicate]C ++如何在文本文件中拆分字符串[重复]
【发布时间】:2014-11-04 11:37:16
【问题描述】:

我有一个文本文件,想通过拆分文件中的字符串将其提取到两个文本文件中。

文本文件如下所示:

列表.txt

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

我想在一个新的文本文件中提取“A00.0”部分,在另一个文本文件中提取描述部分。

代码.txt

A00.0
A01
B07.2

Desc.txt

Description
Some other text here
Lorem Ipsum

谁能帮帮我?

【问题讨论】:

  • 打开一个输入流和两个输出流。从输入流中读取一行。拆分输入行。写第一个必须流一个,第二个必须流两个。重复读/拆分/写直到完成。关于 SO 的问题和答案已经解决了每个步骤。

标签: c++ string split string-split


【解决方案1】:

您不必真正“拆分”它。

#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;
}

【讨论】:

  • 它工作正常,谢谢:)
【解决方案2】:

至于 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++”、“文本分隔符读取”和类似关键字的 SO 的单一研究来解决。

【讨论】:

    【解决方案3】:
    1. 使用 getline() 从 src 文件中读取每一行。 如: while( getline(srcfile,str) ) { //todo:: }
    2. 使用 find_first_of() 分割此行字符串。 如: 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 输出到您的文件中;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2010-09-21
      相关资源
      最近更新 更多