gpt4 book ai didi

c++ - C++新手尝试从文件中读取同一主题的两件事

转载 作者:行者123 更新时间:2023-12-03 07:21:58 25 4
gpt4 key购买 nike

我正在尝试从书店的输入文件中读取书籍信息。我使用getline读取文件,但是,有些书有两位作者和两种不同格式,这就是我遇到的问题。我需要我的输出将两个名称都列为作者,并且两种格式都正确,直到到达作者点为止,我的输出都还可以,而且我的格式也正确。以下是到目前为止的txt文件和代码。一些声明的变量用于程序的其余部分。

**C++ Code:**

string str;
string title;
string authors[4];
string publisher;
string ISBN;
string filename;
string Format;
double cost;
int yearpublished;
int copies;
int numOfcopies;
int numOfauthors;
int numFormats;
char userChoice;
int count = 0;
int num = 0;
int input = 0;

ifstream infile;
int i;

cout << "please enter the name of the file you wish to input:" << endl;
getline(cin, filename);

infile.open(filename.c_str());

if (!infile) {
cout << "file not found!!!" << endl;
exit(0);
}
while (!infile.eof()) {
getline(infile, title);
cout << "Title: " << title <<endl;
getline(infile, ISBN);
cout << "ISBN: " << ISBN << endl;
getline(infile, publisher);
cout << "publisher:" << publisher << endl;
string yearpublished;
getline(infile, yearpublished);
cout << "Year published: " << yearpublished << endl;
string cost;
getline(infile, cost);
cout << "Price:" << cost << endl;
string numOfcopies;
getline(infile, numOfcopies);
cout << "Copies in stock:" << numOfcopies << endl;
string numOfauthors;
getline(infile, numOfauthors);
cout << "Number of authors: " << numOfauthors << endl;
getline(infile, authors[4]);
cout << "Book authors:" << authors[4] << endl;
string numFormats;
getline(infile, numFormats);
cout << "Number of formats:" << numFormats << endl;
getline(infile, Format);
cout << "Book format:" << Format << endl;
string NumPages;
getline(infile, NumPages);
cout << "Number of Pages:" << NumPages << endl;

最佳答案

查看std::vector。这使您可以使用大小可变的数组。检索到作者数量后,可以将for循环与getline一起使用,以获取正确的作者数量。或者,您将它们全部用逗号分隔在一行上,以将其拆分,如下所示:
Parse (split) a string in C++ using string delimiter (standard C++)
您可以将各个名称放入 vector 中。

关于c++ - C++新手尝试从文件中读取同一主题的两件事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64829171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com