ここで何か助けが得られることを願っていました。来週、txt ファイルから一連のデータを配列に読み取り、結果を出力する課題があります。データの形式は次のとおりです。
"マクベス"、"ウィリアム シェイクスピア"、"41.04"、"161"、"23"、"978-88-5985-004-5"
「クリスマス キャロル」、「チャールズ ディケンズ」、「98.74」、「167」、「547」、「978-26-2885-780-7」。.
.
.
各行には、後で使用するために保存する必要がある 6 つの情報があります。正しいサイズの動的配列を作成するために、テキストの行数をカウントするコードを書くことになっています。私はそれをカバーしました。39行のエントリがあります。次に、txt ファイルを読み取り、そのすべてのデータを、作成した配列内の対応するオブジェクトに保存する関数を作成することになっています。
どの方法を使えばいいのかわからず、チュートリアルや説明を数日間探し回っています。私はファイルと解析の経験が非常に限られているため、少し経験が浅い場合はご容赦ください。これまでの私のコードは次のとおりです。
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
class Author
{
public:
private:
string fname, lname;
};
class Book
{
friend ofstream& operator<<(ofstream&, Book);
public:
Book();
private:
string bookName;
Author author;
double price;
int qtyOnHand;
int qtySold;
double revenue;
string ISBN;
};
Book :: Book()
{
}
int getLineNumber(ifstream &);
void parseData(ifstream &, Book []);
//void sortBookList(Book[], int, int);
int main()
{
int numberOfBooks;
//open the file from which to read the data
ifstream myFile;
myFile.open("Book List.txt");
//function to find out how many objects to create
numberOfBooks = getLineNumber(myFile);
//create an array with that many objects
Book *bptr;
bptr = new Book[numberOfBooks];
//function to read information from file into array of objects
parseData(myFile, bptr);
//loop to call sorting function and output function based on 4 different criteria
//close the file explicitly
return 0;
}
int getLineNumber(ifstream &myFile)
{
int counter = 0;
string myString;
while(!myFile.eof())
{
getline(myFile, myString);
counter++;
}
myFile.close();
counter --;
return counter;
}
void parseData(ifstream &myFile, Book bookPtr[])
{
}
したがって、私の問題を要約すると、テキスト ファイルから配列にデータを解析する方法がわかりません。助けてくれる人には、事前に非常に感謝しています!乾杯。
編集: コードをいじってみましたが、正しい方向に一歩進んだと思いますが、まだ少し迷っています。parseData 関数について私が持っているものは次のとおりです。
void parseData(ifstream &myFile, Book bookPtr[])
{
string dummyLine;
string word, line;
myFile.open("Book List.txt");
getline(myFile, dummyLine);
string data[6];
while(!myFile.eof())
{
getline(myFile, line, '\n');
for (size_t i = 0; i < line.size(); ++i)
{
char c = line[i];
if(c == ',' || c == '\n')
{
if(!word.empty())
{
data[i] = word;
word.clear();
}
}
else
{
word += c;
}
}
if(!word.empty())
{
//cout << word << endl;
}
}
}