我正在创建一个程序,该程序可以从文件中读取作者,标题和卷数并打印出标签,
(例如。 亚当斯 世界完整史 第 1 卷,共 10 卷
亚当斯 世界完整史 第 2 卷,共 10 卷等(
为了使它正确读取而不是无限循环,我不得不将所有变量更改为字符串。但是,为了将来参考卷号,我需要它是 int,以便我可以比较数量。 我关于使用 do-while 循环推进代码的想法被注释以说明为什么我希望 vnum 具有 int 值。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
string author;
string title;
string vnum;
int counter=1;
fin.open("publish.txt", ios::in);
while (!fin.eof())
{
getline(fin, author);
getline(fin, title);
getline(fin, vnum);
//do
//{
cout << author << endl;
cout << title << endl;
cout << "Volume " << counter << " of " << vnum << endl;
cout << endl;
//counter++;
//} while(counter < vnum);
}
fin.close();
return 0;
}
我正在读取的文件:
亚当斯
世界完整史
10
塞缪尔斯
我的犯罪生活
阿拉伯数字
鲍姆
巫师故事
6
首先,避免使用
while (!fin.eof())
请参阅为什么"while ( !feof (file(("总是错误的?以了解它会导致的问题。
谈到你的任务,我建议:
- 创建一个
struct
来保存数据。 - 添加一个函数以从
std::istream
读取struct
的所有成员。 - 添加一个函数,将
struct
的所有成员写入std::ostream
。 - 简化
main
以使用上述内容。
这是我的建议:
struct Book
{
std::string author;
std::string title;
int volume;
};
std::istream& operator>>(std::istream& in, Book& book);
std::ostream& operator<<(std::ostream& out, Book const& book);
这将有助于简化以下main
:
int main()
{
ifstream fin;
Book book;
// Not sure why you would need this anymore.
int counter=1;
fin.open("publish.txt", ios::in);
while ( fin >> book )
{
cout << book;
++counter;
}
return 0;
}
读取和写入Book
的函数可以是:
std::istream& operator>>(std::istream& in, Book& book)
{
// Read the author
getline(in, book.author);
// Read the title
getline(in. book.title);
// Read the volume
in >> book.volume;
// Ignore rest of the line.
in.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
return in;
}
std::ostream& operator<<(std::ostream& out, Book const& book)
{
out << book.author << std::endl;
out << book.title << std::endl;
out << book.volume << std::endl;
return out;
}