簡體   English   中英

C ++從文本文件中讀取字符串,並將每個單詞保存到鏈表中

[英]C++ Read String from Text file and save word by word into linkedlist

我被分配編寫一個用於房間預訂系統的C ++程序。 我知道如何逐行讀取文本文件並將其保存。 但是我的問題是如何逐字讀取文本文件。

這是我擁有的文本文件:

1-Reserved-2018-12-23-Lecture Room-13
2-Reserved-2018-11-34-Tutorial Room-15
3-Not Reserved-0-0-0-Design Studio-18
4-Reserved-2018-11-16-Lecture Room-14
5-Not Reserved-0-0-0-Exam Hall-18

我想讀取文本文件並將單詞保存到節點中。 (例如IDdatatypeofRoom等。)在C ++中有什么方法可以這樣做?

這是我的課:

class room {

public:

    int length;
    int initial;

    enum class roomType { main_hall, exam_hall, lecture_room, tutorial_room, design_studio, meeting_room };
    struct node {

        string data;
        int id;
        int capacity;
        int year, month, day;
        int deleteDate;
        roomType type;
        node* next;
    };
    node* front;
    node * tail;
    room() {
        length=0;
        initial=1;

        front = NULL;
        tail = NULL;
    }

    bool isFull () { return length>=20; }


    // Add Rooms
    void room::addRoom() {
        system("cls");

   if (isFull()) {

       cout<<"    No more than 25 rooms are allowed\n"<<endl;
       return;
   }

        cout << "Enter the capacity" << endl;
        int a;
        cin >> a;

        node* temp = new node();
        temp->data = "Not Reserved";
        temp->id = initial;
        temp->year = 0;
        temp->month = 0;
        temp->day = 0;
        temp->deleteDate = 0;

        initial++;
        temp->capacity = a;
        temp->next = NULL;
        if (front == NULL && tail == NULL)
        {
            front = temp;
            tail = temp;
        }
        else {
            tail->next = temp;
            tail = temp;
        }
        cout << "Choose The type" << endl;
        cout << "1- Main Hall \t 2- Lecture Room \t 3- Exam Hall \t 4- Meeting Room \t 5- Design Studio \t 6- Tutorial Room" << endl;
        int t;
        cin >> t;
        if (t == 1)
        {
            temp->type = roomType::main_hall;

        }
        else if (t == 2)
        {
            temp->type = roomType::lecture_room;

        }
        else if (t == 3)
        {
            temp->type = roomType::exam_hall;


        }
        else if (t == 4)
        {
            temp->type = roomType::meeting_room;


        }
        else if (t == 5)
        {
            temp->type = roomType::design_studio;


        }
        else if (t == 6)
        {
            temp->type = roomType::tutorial_room;


        }
        else {cout << "Wrong Input!" << endl;}
        length++;
        cout<<"\n Successfully Created!\n\n";
        system("pause");
        save();
    }
    void reserveRoom()
    {
        system("cls");
        show();
        cout << "=============================================================" << endl;
        cout << "Enter the room ID you want to Book !" << endl;
        int id;
        cin >> id;
        node* tmp = front;

        while (tmp != NULL) {
            if (tmp->id == id) {
                if(tmp->data == "Not Reserved"){
                tmp->data = "Reserved";
                int y,m,d;

                cout << "Enter the year " << endl;
                cin >> y;

                cout << "Enter the month " << endl;
                cin >> m;

                cout << "Enter the day " << endl;
                cin >> d;

                tmp->year = y;
                tmp->month = m;
                tmp->day = d;
                tmp->deleteDate = y+m+d;


                cout << "Room Reserved!" << endl;
                }
                else{
                    cout << "This room has been reserved!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;

                }
            }
            tmp = tmp->next;
        }
        system("pause");
        room::save();

    }
};

我知道如何逐行讀取文本文件並將其保存。 但是我的問題是如何逐字讀取文本文件。

這是我擁有的文本文件:

 1-Reserved-2018-12-23-Lecture Room-13 2-Reserved-2018-11-34-Tutorial Room-15 3-Not Reserved-0-0-0-Design Studio-18 4-Reserved-2018-11-16-Lecture Room-14 5-Not Reserved-0-0-0-Exam Hall-18 

繼續我上面的評論,每當您遇到將單詞分隔成一行並在單詞之間使用分隔符的情況時,一種標准的方法是將每一行都用getline組成一個string ,然后從該行創建一個stringstream ,將每個單詞讀為一個stringgetline與指定的分隔符一起使用。

為什么要閱讀與線getline和閱讀stringstreamgetline一遍嗎?

答:線路控制。

雖然您可以簡單地使用getline和分隔符直接讀取文件,分隔符將每個單詞分開,但是您如何知道一行結束和下一行開始的時間呢? 當您指定與getline一起使用的定界符時, getline會一直讀取,直到找到定界符或已讀完輸入或str.max_size字符str.max_size 參見cppreference.com-std :: getline 因此,在這種情況下,行尾'\\n'沒有特殊含義。

但是,如果你讀了整條生產線成string ,然后創建一個stringstream從行,你知道你只能讀,直到最后的行為,將觸發輸入端的文件狀態。 因此,即使您使用帶有分隔符的getline ,它現在也只能讀取到行尾。

一個使用此方法並使用數據文件的簡短示例將說明如何將每一行分成單詞,然后將其添加到列表的每個節點,例如

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main (int argc, char **argv) {

    std::string line;   /* string to hold each line */

    if (argc < 2) {     /* validate at least 1 argument given */
        std::cerr << "error: insufficient input.\n"
                "usage: " << argv[0] << " filename\n";
        return 1;
    }

    std::ifstream f (argv[1]);  /* open file */
    if (!f.is_open()) {         /* validate file open for reading */
        perror (("error opening file " + std::string(argv[1])).c_str());
        return 1;
    }

    while (getline (f, line)) {         /* read each line into line */
        std::string word;               /* string to hold words */
        std::stringstream s (line);     /* create stringstream from line */
        while (getline (s, word, '-'))  /* read hyphen separated words */
            std::cout << word << '\n';  /* output words */
        std::cout << '\n';  /* tidy up with newline between data */
    }
}

輸入文件示例

$ cat ../dat/hyphenstr.txt
1-Reserved-2018-12-23-Lecture Room-13
2-Reserved-2018-11-34-Tutorial Room-15
3-Not Reserved-0-0-0-Design Studio-18
4-Reserved-2018-11-16-Lecture Room-14
5-Not Reserved-0-0-0-Exam Hall-18

使用/輸出示例

注意,上面的代碼只是在與每行分隔的單詞之間簡單地輸出一個附加的'\\n' 您將編寫邏輯(也許使用計數器,例如,進行任何需要的轉換為stoi )以將值轉換為整數值並將每個值存儲在其適當的字段中。

$ ./bin/getline_hyphen ../dat/hyphenstr.txt
1
Reserved
2018
12
23
Lecture Room
13

2
Reserved
2018
11
34
Tutorial Room
15

3
Not Reserved
0
0
0
Design Studio
18

4
Reserved
2018
11
16
Lecture Room
14

5
Not Reserved
0
0
0
Exam Hall
18

您還可以從每一行中刪除分隔符,創建一個不帶連字符的單獨stringstream ,並使用>>讀取和轉換每個節點的值。 (第二種方法留給您)

仔細檢查一下,如果您還有其他問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM