私のコレクション内の書籍にインデックスを付けるプログラムを作成することになっています。構造体には、タイトル、著者、出版者などの通常の書籍情報が含まれています。しかし、出力は得られません。 1つの問題は、タイトルにスペースが含まれることです。ファイルの内容を構造体に追加する
/* Book Inventory assignment 2 by Heath Martens. */
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <cstring> // I had to throw this in in order to get memcpy to work.
using namespace std;
typedef struct book{
char title[100];
char author[100];
char publisher[100];
float price;
int isbn;
int pages;
int copies;
} Book;
Book collection[100];
int currentIndex;
void
indexBook(Book *my_book)
{
memcpy(&collection[currentIndex], my_book, sizeof(Book));
currentIndex++;
}
void
readfile(void)
{
fstream my_stream;
string line = " ";
my_stream.open("input.txt");
int i=0;
for (i = 0; i < currentIndex; i++)
{
while (getline(my_stream, line))
{
cin >> line >> collection[i].title;
cin >> line >> collection[i].author;
cin >> line >> collection[i].publisher;
cin >> line >> collection[i].price;
cin >> line >> collection[i].isbn;
cin >> line >> collection[i].pages;
cin >> line >> collection[i].copies;
}
}
my_stream.close();
}
void
printCollection(void)
{
int i;
for (i = 0; i < currentIndex; i++)
{
cout << "Title: " << "\t\t" << collection[i].title << endl;
cout << "Author: " << "\t" << collection[i].author << endl;
cout << "Publisher: " << "\t" << collection[i].publisher << endl;
cout << "Price: " << "\t\t" << collection[i].price << endl;
cout << "ISBN: " << "\t\t" << collection[i].isbn << endl;
cout << "Pages: " << "\t\t" << collection[i].pages << endl;
cout << "Copies: " << "\t" << collection[i].copies << endl;
}
}
void printCollection(void);
int
main(void)
{
currentIndex = 0;
Book *my_book = new Book;
indexBook(my_book);
readfile();
printCollection();
delete my_book;
return 0;
}
ここに私が使用するように与えられたtxtファイルがあります。
Magician: Apprentice
Raymond E. Feist
Spectra (January 1, 1994)
5.02
0553564943
512
1
Magician: Master
Raymond E. Feist
Spectra (January 1, 1994)
7.99
0553564935
499
1
ここに提供されているいくつかの例に基づいて更新されたコードがあります。
void
readfile(void)
{
fstream my_stream ("input.txt");
if(!my_stream)
{
return;
}
string line = " ";
int i=0;
for (i = 0; i < currentIndex; i++)
{
if(!std::getline(my_stream, line))
{
break;
}
memcpy(collection[currentIndex].title, line.c_str(), std::min(sizeof(collection[currentIndex].title), line.size()));
memcpy(collection[currentIndex].author, line.c_str(), std::min(sizeof(collection[currentIndex].author), line.size()));
memcpy(collection[currentIndex].publisher, line.c_str(), std::min(sizeof(collection[currentIndex].publisher), line.size()));
my_stream >> collection[currentIndex].price;
my_stream >> collection[currentIndex].isbn;
my_stream >> collection[currentIndex].pages;
my_stream >> collection[currentIndex].copies;
my_stream.ignore();
if(!my_stream)
{
break;
}
}
C++を使用している場合は、char配列の代わりに 'std :: string'を使用することを検討する必要があります。 –
データファイルを構造体に読み込む方法の例については、インターネットで "stackoverflow C++ read file struct"を検索してください。あまりにも多くの同様の質問と回答があります。 –
ヒント:txtファイルにいくつの本があるかにかかわらず、一度だけ 'currentIndex'をインクリメントするようです。 –