C++ 用字符串和整数逐行读取文件
我正在尝试从以下文件中读取信息:C++ 用字符串和整数逐行读取文件,c++,class,C++,Class,我正在尝试从以下文件中读取信息: 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 P
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);
}
一种简化方法是,因为
getline
返回一个istream
,在条件下直接测试它:
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
}
您可以为您的书籍类定义一个提取运算符来封装内容,也可以使用标准的内置提取运算符(>>)来保存临时变量和转换:
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);
}
std::ifstream&operator>>(std::ifstream&str,book&b)
{
str>>b.title>>b.publisher>>b.num\u页;
返回str;
}
std::ifstream-infle;
书籍添加;
病媒采集;
而(填充>>添加)
{
收集。推回(添加);
}
atoi函数出现错误。Xcode表示没有匹配的函数。line参数是否正确?@iamthewalrus我已将其更新为line.c_str()
,请刷新页面。@iamthewalrus如果您觉得答案有用,您能接受吗?谢谢如果您有时间,请检查我在新编辑的代码中的最后一个问题!你能试着调试一下代码吗?放一个你不能这样做。标题和出版商中有空格。
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
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
}
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);
}