从 txt 文件读取时,C++ 重载流 I/O 运算符

C++ overload the stream I/O operators when reading from a txt file

我有一个文本文件,其中包含图书馆模拟程序的书籍信息,这是一个示例:

P.G. Wodehouse, "Heavy Weather" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
Isaac Asimov, "The Gods Themselves" (288 pp.) [UM.824 AVAILABLE FOR LENDING]
Olaf Stapledon, "Odd John" (224 pp.) [LN.171 AVAILABLE FOR LENDING]
...etc

我是 C++ 的新手,我把它写成一个开始,但是正如你所看到的,我需要的每条数据之间没有明确的分离,我不知道如何轻松地分离它们,拜托帮助:

istream& operator<<(istream& in, LibraryBook& b){
    string author,title,classification,status;
    int pages;
    in >> author >> title >> pages >> classification >> status;
    return in;
}

我会使用 getline 然后使用字符串函数来提取字段:

string str;
getline(in, str);

string::size_type k1, k2;

k1 = 0;
k2 = str.find(',');
string author = str.substr(k1, k2);

k1 = str.find('"');
k2 = str.find('"', k1);
string title = str.substr(k1, k2);

k1 = str.find('(');
k2 = str.find(' ', k1);
string temp = str.substr(k1+1, k2-k1);
int pages = atoi(temp.c_str());
...      

这是一个解决方案。它使用 std::getline, std::istream::ignore and std::istream::operator>>.

std::istream& operator>>(std::istream& in, LibraryBook& b){
    // Read author name until ',':
    std::getline(in, b.author, ',');
    // Ignore the space and the quotation mark:
    in.ignore(2);
    // Read title until quotation mark:
    std::getline(in, b.title, '"');
    // Ignore the space and the left bracket:
    in.ignore(2);
    // Read the page amount:
    in >> b.pages;
    // Ignore " pp.) [":
    in.ignore(7);
    // Read the classification:
    in >> b.classification;
    // Ignore the space:
    in.ignore(1);
    // Read status until ']':
    std::getline(in, b.status, ']');
    // Ignore the last newline character:
    in.ignore(1);
    return in;
}