C ++ не получает все строки из файла .txt при токенизации - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь прочитать в моем текстовом файле, который содержит список книг. Однако, когда я выводил файл, в котором я читал, я обнаружил, что некоторые из них не учтены. Мне интересно, возникает ли проблема, когда я пытаюсь токенизировать файл.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <string>
#include <conio.h>
#include <cctype>
using namespace std;

typedef struct
{
    int shelf;
    int level;
} LOCATION_TYPE;

typedef struct
{
    char isbn[14];
    char author[40];
    char title[40];
    char publisher[40];
    int year;
    char genre[20];
    char price[10];
    char quantity[3];
    LOCATION_TYPE location;

} BOOK_TYPE;

void menu();
void list(BOOK_TYPE book[], int total_book);
void search(BOOK_TYPE students[], int total_student);

int main(void)
{
    BOOK_TYPE book[100];
    ifstream input("booklist.txt"); // read input from a text file.
    if (!input)  // check error.
    {
        cout << "Error opening file.\n";
        exit(100); // testing if the text file is connected
    }
    else
    {

        char delim[] = ",";
        char temp[100];
        int index = -1, choice;

        input.getline(temp, 100, '\n');

        while(input)
        {
            char* token = strtok(temp, delim);

            strcpy(book[++index].isbn, token);
            strcpy(book[index].author, strtok(NULL, delim));
            strcpy(book[index].title, strtok(NULL, delim));
            strcpy(book[index].publisher, strtok(NULL, delim));
            book[index].year = atoi(strtok(NULL, delim));
            strcpy(book[index].price, strtok(NULL, delim));
            strcpy(book[index].quantity, strtok(NULL, delim));
            book[index].location.shelf = atoi(strtok(NULL, delim));
            book[index].location.level = atoi(strtok(NULL, delim));
            strcpy(book[index].genre, strtok(NULL, delim));

            // clear unwanted whitespace
            if (input.peek() == '\n')
                input.ignore(256, '\n');

            // read next number
            input.getline(temp, 100, '\n');
            //token = strtok(book[++index], delim);
        }
        input.close();

        system("cls");
        menu();
        cin >> choice;
        while (choice != 0)
        {
            if (choice == 1)
            {
                list(book, index);
            }

            else if (choice == 2)
            {
                search(book, index);
            }

            else
            {
                system("cls");
                cout << "Invalid input. Please key in number 0-4.\n";
                system("pause");
            }
            system("cls");
            menu();
            cin >> choice;
        }
    }
    return 0;
}

void menu()
{
    cout << "UNDERGROUND BOOKS" << endl;
    cout << "1. List all books record" << endl;
    cout << "2. Search books" << endl;
    cout << "3. Add books" << endl;
    cout << "4. Delete books" << endl;
    cout << "0. Exit" << endl;
    cout << "What would you like to do?" << endl;
}

void list(BOOK_TYPE book[], int total_book)
{
    system("cls");
    for (int i = 0; i < total_book; i++)
    {
        cout << left << setw(15) << "ISBN" << setw(20) << "Author" << setw(35) << "Title"
            << setw(25) << "Publisher" << setw(7) << "Year" << setw(15) << "Genre"
            << setw(4) << "Qty" << setw(6) << "Price" << endl;
        cout << "________________________________________________________________________________________________________________________________\n" << endl;

        cout << left << setw(15) << book[i].isbn
            << setw(20) << book[i].author
            << setw(35) << book[i].title
            << setw(25) << book[i].publisher
            << setw(7) << book[i].year
            << setw(15) << book[i].genre
            << setw(4) << book[i].quantity
            << setw(6) << book[i].price << endl << endl
            << "(Located at shelf " << book[i].location.shelf << " level " << book[i].location.level << ")" << endl << endl;
        cout << "________________________________________________________________________________________________________________________________" << endl;

    }
    system("pause");
}


void search(BOOK_TYPE book[], int total_book)
{
    char keyword[55];
    char* substring;
    char tempKeyword[20];

    system("cls");
    // Prompt and get keyword to search student
    cout << "Enter ISBN, book title or author name to search: ";
    while (getchar() != '\n');
    cin.getline(keyword, 55);

    for (int i = 0; i < (int)strlen(keyword); i++)
    {
        keyword[i] = toupper(keyword[i]);   //capitalize all of the character
    }
    for (int i = 0; i < total_book; i++)
    {
        substring = strstr(book[i].isbn, keyword);
        if (substring)
        {
            cout << left << setw(15) << "ISBN" << setw(20) << "Author" << setw(35) << "Title"
                << setw(25) << "Publisher" << setw(7) << "Year" << setw(15) << "Genre"
                << setw(4) << "Qty" << setw(6) << "Price" << endl;
            cout << "________________________________________________________________________________________________________________________________\n" << endl;

            cout << left << setw(15) << book[i].isbn
                << setw(20) << book[i].author
                << setw(35) << book[i].title
                << setw(25) << book[i].publisher
                << setw(7) << book[i].year
                << setw(15) << book[i].genre
                << setw(4) << book[i].quantity
                << setw(6) << book[i].price << endl << endl
                << "(Located at shelf " << book[i].location.shelf << " level " << book[i].location.level << ")" << endl << endl;
            cout << "________________________________________________________________________________________________________________________________" << endl;

        }

        else if (strstr(book[i].author, keyword) != 0)
        {
            cout << left << setw(15) << "ISBN" << setw(20) << "Author" << setw(35) << "Title"
                << setw(25) << "Publisher" << setw(7) << "Year" << setw(15) << "Genre"
                << setw(4) << "Qty" << setw(6) << "Price" << endl;
            cout << "________________________________________________________________________________________________________________________________\n" << endl;

            cout << left << setw(15) << book[i].isbn
                << setw(20) << book[i].author
                << setw(35) << book[i].title
                << setw(25) << book[i].publisher
                << setw(7) << book[i].year
                << setw(15) << book[i].genre
                << setw(4) << book[i].quantity
                << setw(6) << book[i].price << endl << endl
                << "(Located at shelf " << book[i].location.shelf << " level " << book[i].location.level << ")" << endl << endl;
            cout << "________________________________________________________________________________________________________________________________" << endl;

        }
    }
    system("pause");
}

Вот мой список книг, который у меня есть в текстовом файле:

9781785785719,Yasha Levine,Surveillance Valley,Icon Books,2019,57.95,3,1,1,Political Science
9780241976630,John Maeda,How to Speak Machine,Portfolio UK,2019,89.95,2,1,1,Non-Fiction
9781119055808,Andre De Vries,R For Dummies,John Wiley,2015,107.77,4,1,2,Design
9780062018205,Dan Ariely,Predictably Irrational,Harper Collins,2010,39.90,2,1,1,Legal opinion
9780008327613,John Waish,The Globalist,Harper Collins,2019,109.90,2,1,1,Non-Fiction
9780525538349,John Doerr,Measure What Matters,Penguin LCC,2018,86.95,2,1,2,Management
9780807092156,Viktor Frankl,Man's Search for Meaning,Random House,2019,49.90,3,1,3,Biography
9780809875214,John Wick,The Assasinate of a Gang,Tree Production,2014,39.00,4,2,2,Fiction
9788373191723,J.R.R Tolkien,The Lord of the Rings,Allen & Unwin,1954,120.45,6,3,1,Fantasy Adventure
9783791535661,Lewis Carroll,Alice's Adventure in Wonderland,Macmillan,1865,100.25,5,3,2,Fantasy Fiction
9781517322977,Mikhail Bulgakov,The Master and Margarita,Penguin Books,1967,125.00,7,3,3,Romance Novel
9780676516197,Vladmir Nabokov,Lolita,Olympia Press,1955,98.25,3,3,1,Tragicomedy
9781095627242,Anna Sewell,Black Beauty,The Jarrold Group,1877,60.25,2,3,2,Fiction Novel
9788497592581,Umberto Eco,The Name of the Rose,Bompiani,1980,45.65,7,1,3,Historical Fiction
9780545790352,J.K.Rowling,Harry Potter and the Sorcerer's Stone,Arthur A. Levine,2015,44.87,1,3,1

Я управляю выводить только до John Wick (8-я строка из текстового файла), когда в меню пользователя отображается «1» для отображения списка книг.

...