从文本文件中读取并通过定界符分开

Read from text file and seperate by a delimiter

本文关键字:定界符 文本 文件 读取      更新时间:2023-10-16

我正在尝试从文本文件中阅读,然后尝试将它们放在对象中。

,但我不确定如何将一条线分开为两个变量(作为定界符的空间(。

文本文件格式如下(前2个条目(:

    Text1 [txt1]
    This is a description of text 1.More description of Text 1 here blah       blah blah.
    Text2 [txt2]
    This is the description of text 2.

我想将它们分为三个sperate变量,一个用于名称(text1(,类型是方括号([txt1(,最后是描述(这是文本1的描述。(

我到目前为止的代码不会分开text1和[txt1]:

    if (myfile.is_open()) {
    string buffer;
    string currentText= "empty";
    string currentType= "empty";
    string currentDescription = "empty";
    while (!myfile.eof()) {
        getline(myfile, buffer); // Would like to seprate this line into two variables
        currentText = buffer;
        if (buffer == "") continue;
        getline(myfile, buffer);
        currentDescription = buffer;
        if (buffer == "") continue;
        TextObj newtext(currentText, iWantToEnterTypeHere, currentDescription);
        this->textVector.push_back(newText);
    }
    myfile.close();

我希望这很有意义,我将感谢任何帮助。欢呼

#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
int main() {
    fstream myfile;
    myfile.open ("example.txt");
    if (myfile.is_open()) {
        string line;
        while (getline (myfile,line)) {
        vector<string> tokens;
        const string s =  line;
        char delim =' ';
        stringstream ss(s);
        string item;
        while (getline(ss, item, delim)) {
            tokens.push_back(item);
        }   
        getline (myfile,line);
        tokens.push_back(line);
        //Here you can create object using token[0], token[1], token[2] and can remove cout statements
        for(int i = 0; i < tokens.size(); i++) {
                cout << tokens[i] << endl;
        } 
        cout<<"=================n";
     }
    }
    myfile.close();
    return 1;
}

我希望这会有所帮助。您可以根据注释块中指定的对象创建对象,并删除COUT语句。添加了它们只是为了添加澄清。