结构,数组和函数C ++

时间:2015-07-26 05:12:19

标签: c++ arrays function struct

我完全坚持这项任务。我首先在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;
} 

3 个答案:

答案 0 :(得分:5)

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

#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. 当您拥有&#34; main()&#34;中的所有内容时,您的所有代码都可以看到所有变量。

  2. 当您将所有内容都移到单独的功能中时,这些功能将无法再显示&#34;请参阅&#34;这些变量。

    这称为"scope"

  3. 一种解决方案是将所有内容放回&#34; main()&#34;。这很糟糕。

    另一个解决方案是让你的变量全局化。这也是坏事。

    一个好的解决方案是在&#34; main()&#34;中声明需要共享的变量,然后将它们作为parameters传递。这就是我上面所说的。

  4. 更好,更高级的解决方案可能是将您的计划重构为classes

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

    一个。您不再需要阅读整个文件只是为了找到#/元素 - 您可以随时添加新元素。

    湾你总是可以查询&#34; vector.size()&#34;找到当前的#/元素。

  6. 还有其他问题。

  7. 我希望有帮助...如果您有任何问题,请回复。

答案 1 :(得分:0)

一些事情:
- 您的结构不需要在setStruct函数内部,setStruct应该用于将数据发送到现有结构(下面的示例)
-setArray在被调用时没有被传递任何参数(它需要(int &arraySize, struct bookTable *Book[]))而你的其他一些函数也没有,这意味着它们实际上没有任何数据修改。
应该像这样调用它们: setArray(size of array, struct being passed to it);

此外,还应该单独定义setStruct和struct的示例:

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()拆分成一堆函数,除了使代码模块化和清晰之外,你还没有

另外,发布你所获得的确切错误会有所帮助,因为我想即使在你解决了我提到的这些事情后我也可能无法正常工作

答案 2 :(得分: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++;
}

您传递一个使用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 - 希望这会有所帮助。