动态变量基于txt文件

时间:2016-01-25 15:49:24

标签: c++ pointers range

我必须创建一个学校图书馆作为OOP任务。我发现它很难理解,我的问题是:

int RANGE = total_books;

total_books应代表文本文件中的当前图书。 格式化使它读取3部分信息(标题,作者,流派)。我怎样才能在函数之间指出这个?

我想加载程序并读取文件以查看当前有多少(假设有7本书,因此变量应为7 * 3 = 21)。然后当用户查看文件时,它将显示7本书。

目前它是静态的:我把它设置为21.如果我添加另一本书,它只会阅读前7本书。如果我将它设置为24并且有7本书(根据需要不是8本)它会崩溃。我曾尝试在网上查看这些论坛和其他地方,通过简单的步骤获得了#C ++编程"书,它是我获得此格式代码的地方,但它不是很有用。

#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"
#include "string.h"
#include "conio.h"
#include "fstream"
#include "iostream"
using namespace std;

unsigned int number_of_books = 0; //this is based on the number of books *3
int total_books = number_of_books * 3; //*3 to read 1 more book

class Book
{
  private: // properties
    char Title[16];
    char Author[16];
    char Genre[16];
  public: // methods
    int iDetailsGet(void); 
    int iDetailsShow(void);
    int iRecordWrite(void);             
};

int Book::iDetailsGet(void)
{
  // prompt for the data
  fflush(stdout);
  puts("\n \t !USE_UNDERSCORE_FOR_SPACE!");
  puts("\n \t Please enter the Book name: ");
  fflush(stdin);
  scanf("%s", Title, 16);

  fflush(stdout);
  puts("\n \t Please enter the Author: ");
  fflush(stdin);
  scanf("%s", Author, 16);

  fflush(stdout);
  puts("\n \t Please enter the Genre: ");
  fflush(stdin);
  scanf("%s", Genre, 16);

  // Get total number of lines(books)
  FILE *infile = fopen("books.txt", "r");
  int ch;
  while (EOF != (ch = getc(infile)))
    if ('\n' == ch)
      ++number_of_books; // read from variable above but static.
    printf("%u\n", number_of_books);

  //return to menu
  int main();
} // end method definition

int Book::iDetailsShow()
{
  system("CLS");
  int RANGE = total_books; // should be dynamically read on start up
  string tab[RANGE];
  int i = 0, j = 0;
  ifstream reader("books.txt");
  if(!reader)
  {
    cout << "Error Opening input file" << endl;
    return -1;
  }

  while(!reader.eof())
  {
    if((i + 1) % 3 == 0) // the 3 read title,author,genre then adds new line
      getline(reader, tab[i++], '\n');
    else
      getline(reader, tab[i++], '\t');
  }

  reader.close();
  i = 0;

  while (i < RANGE)
  {
    cout << endl << "Record Number: " << ++j << endl;
    cout << "Title: " << tab[i++] << endl;
    cout << "Author: " << tab[i++] << endl;
    cout << "Genre: " << tab[i++] << endl;
  }
  int main();
} // end method definition

// code for the method: iRecordWrite(void)
int Book::iRecordWrite(void)
{
  ofstream NewBook("books.txt", ios::app);
  if (!NewBook)
  {
    printf("Error Recording Book");
    return -1;
  }
  NewBook << "    " << Title << "     " << Author << "    " << Genre << endl;
  NewBook.close();
  int main();
} // end of method deinition

谢谢!

1 个答案:

答案 0 :(得分:0)

而不是在声明时基于total_books初始化number_of_books,而应该在实际读取 number_of_books之后设置它。变量,无论是全局变量还是范围变量,都不会动态更新。所以,你可以这样:

int number_of_books = 0;

void read_number_of_books() {
    // parse input file for value
    total_books = number_of_books * 3;
}

这就是你要找的东西吗?