[英]Reading a file line by line with strings and integers
我正在嘗試從以下文件中讀取信息:
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類中的向量中。
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
}
您可以為您的book
類定義一個提取運算符以將內容封裝起來,也可以使用標准的內置提取運算符(>>)來保存臨時變量和轉換:
std::ifstream & operator>>(std::ifstream & str, book & b)
{
str >> b.title >> b.publisher >> b.num_of_pages;
return str;
}
std::ifstream infile;
book addition;
std::vector<book> collection;
while ( infile >> addition)
{
collection.push_back(addition);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.