结构体、数组和函数 C++

问题描述 投票:0回答:3

我完全被这项任务困住了。我首先在 int main() 中编写了所有内容,没有任何问题。一切都很顺利!不幸的是,我们的讲师希望将其拆分为多个函数(每个函数少于 35 行)。我已经将其分开,如下所示,但不幸的是我对函数和传递/引用它们的了解(谷歌并没有多大帮助)并不是那么高。我的程序现在根本无法运行。所有“书籍”都会给出错误,所以我不确定我是否错误地传递了结构或数组。请帮忙!

原始txt文件内容如下:

number of books
title
author
price
title
author
price

代码:

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

using namespace std;

void setStruct() {

    struct bookTable {
        string title;
        string author;
        double price;
    };
}

void setArray(int &arraySize, struct bookTable *Book[]) {

    ifstream infile;
    int bookCounter = 0;

    infile.open("books2.txt");

    if (!infile) {
        cout << "Unable to open Books.txt" << endl;
    }

    infile >> arraySize;
    infile.ignore(100, '\n');

    bookTable *Book = new bookTable[arraySize];

    infile.close();
}

void readFile(struct bookTable *Book[]) {

    ifstream infile;
    int bookCounter = 0;

    infile.open("books2.txt");

    for (int i = 0; getline(infile, Book[i].title); i++) {

        getline(infile, Book[i].author, '\n');
        infile >> Book[i].price;
        infile.ignore(100, '\n');

        bookCounter++;
    }

    infile.close();
}

void displayMenu(struct bookTable *Book[]) {
    int menuChoice = 0, bookCounter = 0;
    string findTitle;

    do { cout << "\n===== Bookstore App =====" << endl; 
    cout << "1. Print Books" << endl; 
    cout << "2. Change Price" << endl;
    cout << "3. Quit" << endl; 
    cout << "\nEnter Choice: ";
        cin >> menuChoice;
        if (menuChoice == 1) {
            for (int i = 0; i < bookCounter; i++) {
                cout << "===== BOOK =====" << endl;
                cout << "Title: " << Book[i].title << endl;
                cout << "Author: " << Book[i].author << endl;
                cout << "Price: " << fixed << setprecision(2) << Book[i].price << endl; } }
        else if (menuChoice == 2) { cin.ignore(100, '\n');
            cout << "What is the title of the book? ";
            getline(cin, findTitle, '\n');
            for (int i = 0; i < bookCounter; i++) {
                if (findTitle == Book[i].title) {
                    cout << "Enter New Price: " << endl;
                    cin >> Book[i].price;
                }
                else if (findTitle != Book[i].title) {
                    cout << "Unable to find Book" << endl;
                }}}

        else if (menuChoice < 1 || menuChoice > 3) {

            cout << "Invalid Entry. Please enter 1, 2, or 3 from the options menu." << endl;
        }   } while (menuChoice != 3);
}

void writeFile(int arraySize, struct bookTable *Book[]) {

    ofstream outfile;
    int bookCounter = 0;

    outfile.open("sale2.txt");

    outfile << arraySize << endl;

    for (int i = 0; i < bookCounter; i++) {

        outfile << Book[i].title << endl;
        outfile << Book[i].author << endl;
        outfile << fixed << setprecision(2) << Book[i].price << endl;
    }

    outfile.close();

    delete[] Book;

}

int main() {

    setStruct();
    setArray();
    readFile();
    displayMenu();
    writeFile();

    cout << "\nSale2.txt has been created." << endl;

    return 0;
} 
c++ arrays function struct
3个回答
4
投票

我还没有编译或运行这个,但希望它能让你朝着正确的方向开始:

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

using namespace std;

// This declares "struct bookTable"
// You need to actually define a variable of this type later in your program
struct bookTable {
    string title;
    string author;
    double price;
};

bookTable * setArray(int &arraySize, struct bookTable *Book[]) {
    
    ifstream infile;
    int bookCounter = 0;

    infile.open("books2.txt");

    if (!infile) {
        cout << "Unable to open Books.txt" << endl;
    }

    infile >> arraySize;
    infile.ignore(100, '\n');

    bookTable *Book = new bookTable[arraySize];

    infile.close();

    // This returns an empty array of bookTable[]
    return Book;
}

void readFile(struct bookTable *Book) {
    
    ifstream infile;
    int bookCounter = 0;

    infile.open("books2.txt");

    for (int i = 0; getline(infile, Book[i].title); i++) {

        getline(infile, Book[i].author, '\n');
        infile >> Book[i].price;
        infile.ignore(100, '\n');

        bookCounter++;
    }

    infile.close();
}

void displayMenu(struct bookTable *Book[]) {
    int menuChoice = 0, bookCounter = 0;
    string findTitle;

    do { cout << "\n===== Bookstore App =====" << endl; 
    cout << "1. Print Books" << endl; 
    cout << "2. Change Price" << endl;
    cout << "3. Quit" << endl; 
    cout << "\nEnter Choice: ";
        cin >> menuChoice;
        if (menuChoice == 1) {
            for (int i = 0; i < bookCounter; i++) {
                cout << "===== BOOK =====" << endl;
                cout << "Title: " << Book[i].title << endl;
                cout << "Author: " << Book[i].author << endl;
                cout << "Price: " << fixed << setprecision(2) << Book[i].price << endl; } }
        else if (menuChoice == 2) { cin.ignore(100, '\n');
            cout << "What is the title of the book? ";
            getline(cin, findTitle, '\n');
            for (int i = 0; i < bookCounter; i++) {
                if (findTitle == Book[i].title) {
                    cout << "Enter New Price: " << endl;
                    cin >> Book[i].price;
                }
                else if (findTitle != Book[i].title) {
                    cout << "Unable to find Book" << endl;
                }}}

        else if (menuChoice < 1 || menuChoice > 3) {

            cout << "Invalid Entry. Please enter 1, 2, or 3 from the options menu." << endl;
        }   } while (menuChoice != 3);
}

//  !!! DON'T UNCOMMENT THIS UNTIL YOU FIGURE OUT HOW TO PRESERVE "arraySize" !!!
//      Suggestion: use a C++ "vector<>" instead of an array...
//    void writeFile(int arraySize, struct bookTable *Book[]) {
//    
//      ofstream outfile;
//      int bookCounter = 0;
//    
//      outfile.open("sale2.txt");
//    
//      outfile << arraySize << endl;
//    
//      for (int i = 0; i < bookCounter; i++) {
//    
//          outfile << Book[i].title << endl;
//          outfile << Book[i].author << endl;
//          outfile << fixed << setprecision(2) << Book[i].price << endl;
//      }
//    
//      outfile.close();
//    
//      delete[] Book;
//    
//    }
    
int main() {

    // setStruct();  // Not needed
    struct bookTable *book_table = setArray();  // Allocate space
    readFile(book_table);  // Initialize data
    displayMenu(book_table); // use book_table
    // writeFile(); // TBD

    cout << "\nSale2.txt has been created." << endl;

    return 0;
} 

要点:

  1. 当“main()”中包含所有内容时,所有代码都可以看到所有变量。

  2. 当您将所有内容移至单独的函数中时,函数将无法再“看到”这些变量。

这称为“范围”

  1. 一种解决方案是将所有内容放回“main()”中。 这很糟糕。

    另一个解决方案是使变量全部全局化。 这也很糟糕。

    一个好的解决方案是在“main()”中声明需要共享的变量,然后将它们作为参数传递。 这就是我上面展示的。

  2. 一个更好、更高级的解决方案可能是将你的程序重构为

  3. 由于您使用 C++ 进行编程,并且元素数量可变,因此将数组更改为 C++ vector 可能是一个好主意。 这有几个优点,包括:

    a.您不再需要读取整个文件只是为了查找 #/elements - 您可以简单地添加新元素。

    b.您始终可以查询“vector.size()”来查找当前的#/elements。

  4. 还有其他问题。


0
投票

有几件事:
-您的结构不需要位于 setStruct 函数内部,setStruct 应该用于将数据发送到现有结构(下面的示例)
-setArray 在调用时没有传递任何参数(它需要

(int &arraySize, struct bookTable *Book[])
),其他一些函数也没有传递任何参数,这意味着它们实际上没有任何数据可以修改。
他们应该这样称呼:
setArray(size of array, struct being passed to it);

另外,还有一个关于如何单独定义 setStruct 和结构体的示例:

struct bookTable {
    string title;
    string author;
    double price;
};
void setStruct(&struct x, string title, string author, double price) {
    x.title  = title;
    x.author = author;
    x.price  = price;

}

确保注意每个函数的作用,以便您知道要传递给它们的参数并更好地理解整体代码。
通过将 main() 拆分为一堆函数,除了使代码模块化且易读之外,您实际上并没有做太多事情 此外,发布您遇到的确切错误也会有所帮助,因为我想即使您修复了我提到的这些问题,我也可能无法完美工作


0
投票

void setStruct() { struct bookTable { string title; string author; double price; }; }

您创建一个函数
setStruct()

,然后在其他函数中多次使用它,而无需访问该函数本身。为什么不将结构体放在其全局作用域中,这样您就可以在

Main()
或其他任何地方使用它,并在函数之间自由传递结构体声明?

还有:

for (int i = 0; getline(infile, Book[i].title); i++) { getline(infile, Book[i].author, '\n'); infile >> Book[i].price; infile.ignore(100, '\n'); bookCounter++; }

您传递一个 use 
Book

,就好像它在您声明它并可能定义它的范围内一样。但是,您通过函数传递它 - 这意味着结构类型现在超出范围,需要通过指针访问其元素。所以你的代码需要这样调整:


void readFile(struct bookTable *Book[]) { ifstream infile; int bookCounter = 0; infile.open("books2.txt"); for (int i = 0; getline(infile, Book[i]->title); i++) { getline(infile, Book[i]->author, '\n'); infile >> Book[i]->price; infile.ignore(100, '\n'); bookCounter++; } infile.close(); }

请注意,您曾经 
Book[i].variable

的每个地方现在都是

Book[i]->variable
- 希望这会有所帮助。
    

© www.soinside.com 2019 - 2024. All rights reserved.