简体   繁体   English

缺少数组元素问题

[英]Missing array element issue

This is part of a homework assignment I recently finished.这是我最近完成的家庭作业的一部分。 I am required to use an array of structs to store a library of books by title and author.我需要使用一组结构来按书名和作者存储图书库。 The code is working and running perfectly fine when sorting and displaying author or title alphabetically according to user input.根据用户输入按字母顺序排序和显示作者或标题时,代码运行良好。

The only issue I run into is when it shows all books sorted alphabetically.我遇到的唯一问题是当它显示按字母顺序排序的所有书籍时。 There are 14 books total in the text file used with the assignment, but only 13 books show up when the show all (S) option is entered.与作业一起使用的文本文件中总共有 14 本书,但在输入全部显示 (S) 选项时仅显示 13 本书。

An example of the error would be:错误的一个例子是:

()

Audio for Games (Brandon)

Instead of:代替:

Audio for Games (Brandon)
Beginning LINUX Programming (Stones and Matthew)

My Code:我的代码:


#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

// structure
struct Book {
    string title;
    string author;
};

const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
string pathName;
ifstream lib;

// global variables
int loadData();
void showAll(int count);
void sortByTitle(int count, string title);


int main()
{
    // initialised variables
    int count = 0;
    char selector = 'q', yesNoAnswer = 'n';
    string name;
    string title;

    // asks user for file pathname
    cout << "Welcome to Tommy's Library Database." << endl;
    cout << "Please enter the name of the file: ";
    getline(cin, pathName);
    loadData();
    count = loadData();
    cout << count << " Records loaded successfully." << endl;
    // Switch case menu
    do {
        cout << endl << "Please enter a keyword that corresponds to the list of options: " << endl;
        cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
        cin >> selector;
        selector = toupper(selector);
        switch (selector)
        {
        case 'S':
            sortByTitle(count, title);
            if (count <= 0) {
                cout << " No counts found! " << endl;
            }
            else {
                showAll(count);
            }
            break;
        }
    }
    while (selector != 'q' && selector != 'Q');
    return 0;
}

int loadData()
{
    int count = 0;
    int i = 0;

    lib.open(pathName);
    ifstream lib(pathName);

    if (!lib)
    {
        cout << " Unable to open file path! " << endl;
        return -1;
    }
    while (!lib.eof())
    {
        getline(lib, books[count].title);
        getline(lib, books[count].author);
        count++;
    }
    return count;
}
// displays all book titles beside the author names
void showAll(int count)
{
    for (int i = 0; i < count; i++)
    {
        cout << books[i].title << " " << "(" << books[i].author << ")" << endl;
    }
}
// Sorts by book title.
void sortByTitle(int count, string title) {
    Book temp;
    for (int i = 0; i < count; i++) {
        for (int j = 0; j < count - i; j++) {
            if (books[j].title > books[j + 1].title) {
                temp = books[j];
                books[j] = books[j + 1];
                books[j + 1] = temp;
            }
        }
    }
}

The text file im using with the assignment (books.txt)我在作业中使用的文本文件 (books.txt)

Objects First with Java
Barnes and Kolling
Game Development Essentials
Novak
The Game Maker's Apprentice
Overmars
C++ Programming: From Problem Analysis...
Malik
C++ Programming Lab Manual
Scholl
Beginning LINUX Programming
Stones and Matthew
C++ Programming: Program Design Including...
D. S. Malik
C++ How to Program
Deitel and Deitel
Programming and Problem Solving with C++
Dale, Weems, Headington
Game Character Development with Maya
Ward
Developing Games in Java
Brackeen
C# Programming
Harvey, Robinson, Templeman, Watson
Java Programming
Farrell
Audio for Games
Brandon

当您的书籍数组从 1 开始时,您在showAll()方法中从 0 开始循环,只需从 1 开始循环并转到 count + 1

for (int i = 1; i < count + 1; i++)

Your sort function doesn't work correctly.您的排序功能无法正常工作。 It's off by one and moves an empty element to the first index.它关闭一个并将一个空元素移动到第一个索引。 It would cause undefined behavior if your array were full.如果您的数组已满,则会导致未定义的行为。 Your sort function sorts all elements from 0 to count but it should sort from 0 to count - 1 .您的 sort 函数将所有元素从 0 排序到count但它应该从 0 排序到count - 1 You should fix your sort function ( std::sort usually is faster than bubble sort):您应该修复排序函数( std::sort通常比冒泡排序快):

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

// structure
struct Book {
    string title;
    string author;
};

const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
string pathName;
ifstream lib;

// global variables
int loadData();
void showAll(int count);
void sortByTitle(int count, string title);


int main()
{
    // initialised variables
    int count = 0;
    char selector = 'q', yesNoAnswer = 'n';
    string name;
    string title;

    // asks user for file pathname
    cout << "Welcome to Tommy's Library Database." << endl;
    cout << "Please enter the name of the file: ";
    getline(cin, pathName);
    loadData();
    count = loadData();
    cout << count << " Records loaded successfully." << endl;
    // Switch case menu
    do {
        cout << endl << "Please enter a keyword that corresponds to the list of options: " << endl;
        cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
        cin >> selector;
        selector = toupper(selector);
        switch (selector)
        {
        case 'S':
            sortByTitle(count, title);
            if (count <= 0) {
                cout << " No counts found! " << endl;
            }
            else {
                showAll(count);
            }
            break;
        }
    }
    while (selector != 'q' && selector != 'Q');
    return 0;
}

int loadData()
{
    int count = 0;
    int i = 0;

    lib.open(pathName);
    ifstream lib(pathName);

    if (!lib)
    {
        cout << " Unable to open file path! " << endl;
        return -1;
    }
    while (!lib.eof())
    {
        getline(lib, books[count].title);
        getline(lib, books[count].author);
        count++;
    }
    return count;
}
// displays all book titles beside the author names
void showAll(int count)
{
    for (int i = 0; i < count; i++)
    {
        cout << books[i].title << " " << "(" << books[i].author << ")" << endl;
    }
}
// Sorts by book title.
void sortByTitle(int count, string title) {
    std::sort(books, books + count, [](const auto &lhs, const auto &rhs) {
        return lhs.title < rhs.title;
    });
}

In addition:此外:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using std::cin;
using std::cout;
using std::ifstream;
using std::string;

// structure
struct Book {
    string title;
    string author;
};

const int ARRAY_SIZE = 1000;

// global variables
int loadData(string pathName, Book *books);
void showAll(Book *books, int count);
void sortByTitle(Book *books, int count);


int main()
{
    // initialised variables
    int count = 0;
    char selector = 'q';

    // asks user for file pathname
    cout << "Welcome to Tommy's Library Database.\n";
    cout << "Please enter the name of the file: ";
    string pathName;
    getline(cin, pathName);
    Book books[ARRAY_SIZE];
    count = loadData(pathName, books);
    cout << count << " Records loaded successfully.\n";
    // Switch case menu
    do {
        cout << "\nPlease enter a keyword that corresponds to the list of options: \n";
        cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
        cin >> selector;
        selector = toupper(selector);
        switch (selector)
        {
        case 'S':
            sortByTitle(books, count);
            if (count <= 0) {
                cout << " No counts found! \n";
            }
            else {
                showAll(books, count);
            }
            break;
        }
    }
    while (selector != 'q' && selector != 'Q');
    return 0;
}

int loadData(string pathName, Book *books)
{
    int count = 0;
    ifstream lib(pathName);

    if (!lib)
    {
        cout << " Unable to open file path! \n";
        return -1;
    }
    while (getline(lib, books[count].title))
    {
        getline(lib, books[count].author);
        count++;
    }
    return count;
}
// displays all book titles beside the author names
void showAll(Book *books, int count)
{
    for (int i = 0; i < count; i++)
    {
        cout << books[i].title << " " << "(" << books[i].author << ")\n";
    }
}
// Sorts by book title.
void sortByTitle(Book *books, int count) {
    std::sort(books, books + count, [](const auto &lhs, const auto &rhs) {
        return lhs.title < rhs.title;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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