gpt4 book ai didi

c++ - 使用字符串和整数逐行读取文件

转载 作者:行者123 更新时间:2023-11-28 07:37:38 30 4
gpt4 key购买 nike

我正在尝试从以下文件中读取信息:

The Firm
Dell
512
Fundamentals of Computer Graphics
A K Peters, Ltd.
662
The C++ Programming Language
Addison-Wesley Professional
911
Northwest Airlines
Plymouth Toy & Book
96
Lonely Planet: Europe on a Shoestring
Lonely Planet Publications
1324

该文件列出了书籍,第一行是标题,第二行是出版商,第三行是页数。它重复五本书。我正在尝试读取信息并将它们存储到 Library 类的 vector 中。

class book

{


public:

book();


book(string t, string p, int num);


string getTitle();
string getPublisher();
int getPageNum();


void setTitle(string t);
void setPublisher(string p);
void setPageNum(int num);


string title;
string publisher;
int num_of_pages;

};



class library
{
public:
vector<book> collection;

bool contains(string title);

void addBook(book b);

void readFile(string fileName);
}

这里是 readFile 函数:

   void library::readFile(string fileName)
{
ifstream infile;
infile.open(fileName.c_str());
if (infile.fail())
{
cout<<"Error opening file."<<endl<<endl;
exit(1);
}

book addition;
string line;

while (!infile.eof())
{
getline(infile, addition.title);
getline(infile, addition.publisher);
getline(infile, line);
addition.num_of_pages=atoi(line.c_str());
collection.push_back(addition);
}


collection.push_back(addition);


}

最后一个问题:输出工作不正常。文件中的所有内容都列在标题下。

ostream &operator <<(ostream& out, const book& b1)
{
out<<"TITLE: "<<b1.title<<endl;
out<<"PUBLISHER: "<<b1.publisher<<endl;
out<<"NUMBER OF PAGES: "<<b1.num_of_pages<<endl;

return out;
}

主要代码:

int i;
for (i=0; i<book_library.collection.size(); i++)
{
cout<<book_library.collection[i]<<endl;
}

输出:

TITLE: The Firm
Dell
512
Fundamentals of Computer Graphics
A K Peters, Ltd.
662
The C++ Programming Language
Addison-Wesley Professional
911
Northwest Airlines
Plymouth Toy & Book
96
Lonely Planet: Europe on a Shoestring
Lonely Planet Publications
1324
\311
PUBLISHER:
NUMBER OF PAGES: 0

最佳答案

一个简化可能是,因为 getline 返回一个 istream,直接在 while 条件下测试它:

while (getline(infile, addition.title)) {
getline(infile, addition.publisher);
getline(infile, line);
addition.num_of_pages = atoi(line.c_str()); // string -> int
collection.push_back(addition); // you should push_back in the while loop
}

关于c++ - 使用字符串和整数逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431504/

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