简体   繁体   中英

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

I am assigned to write a c++ program for room booking system. I know how to read a text file line by line and save it. but my problem is how to read text file word by word.

This is the text file I have:

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

I want to read the text file and save the words into it nodes. (Like ID , data , typeofRoom , etc.) Is there any way to do so in C++?

This is my class:

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();

    }
};

I know how to read a text file line by line and save it. but my problem is how to read text file word by word.

This is the text file I have:

 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 

Continuing from my comment above, whenever you are faced with separating words in a line with a delimiter in between the words, a standard approach is the each line into a string with getline and then create a stringstream from the line reading each word into a string using getline with the delimiter specified.

Why Read a Line with getline and Read a stringstream with getline Again?

Answer: line-control.

While you could simply read directly from your file using getline and a delimiter, which would separate each word, how would you know when one line ended and the next line began? When you specify the delimiter to use with getline , getline will read until the delimiter is found or end of input or str.max_size characters have been read. See cppreference.com - std::getline . So there is no special meaning to the line-ending '\\n' in this case.

However, if you read the entire line into a string and then create a stringstream from the line, you know you can only read until the end-of-line as that will trigger the end-of-file condition on input. So even though you are using getline with a delimiter, it can now only read as far as the end of line.

A short example using this approach and using your data file will show how you can separate each line into words that you can then add to each node of your list, eg

#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 */
    }
}

Example Input File

$ 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

Example Use/Output

Note, the code above simply outputs an additional '\\n' between the words separated from each line. You would write logic (perhaps using a counter, and, eg stoi for any needed conversions) to convert the values to integer values and store each in its proper field.

$ ./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

You can also remove the separators from each line, create a separate stringstream without the hyphens and use >> to read and convert the values for each node. (this second approach is left to you)

Look things over and let me know if you have further questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM