【发布时间】:2021-04-14 20:20:21
【问题描述】:
在我的项目中,我有一个 .txt 文件,顶部是书的数量,然后是书名及其作者,以空格分隔,例如:
1
Elementary_Particles Michel_Houllebecq
然后我有一个图书对象的结构
struct book {
string title;
string author;
};
由于有多个书籍和作者,因此存在这些书籍对象的书籍数组。我需要做的是逐字阅读这些内容并将标题分配给 book.title 并将作者分配给 book.author。这是我目前所拥有的:
void getBookData(book* b, int n, ifstream& file) { //n being the number at the top of the file
int count = 0;
string file_string;
while(!file.eof() && count != n-1) {
while (file >> file_string) {
b[count].title = file_string;
b[count].author = file_string;
count++;
}
}
当我使用这些输出运行它时:
cout << book[0].title << endl;
cout << book[0].author << endl;
我明白了:
Elementary_Particles
Elementary_Particles
基本上它只取第一个单词。如何将第一个单词分配给 book.title 并将下一个单词分配给 book.author?
谢谢
【问题讨论】:
-
显然答案是一次阅读两个单词,例如
while (file >> str1 >> str2) { b[count].title = str1; b[count].author = str2; count++; }
标签: c++ file struct ifstream eof