首页 > 解决方案 > 如何逐字读取文件并将这些单词分配给结构?

问题描述

在我的项目中,我有一个 .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?

谢谢

标签: c++filestructifstreameof

解决方案


在这段代码中

while (file >> file_string) {
      b[count].title = file_string;
      b[count].author = file_string;
      count++;
}

你读了一个词并为标题和作者分配了相同的值,不要指望编译器猜测你的意图;)

一些额外的提示和想法:

while(!file.eof()不是您想要的,而是将输入操作放入循环条件中。您可以跳过中间字符串并直接读入title/ author

void getBookData(book* b, int n, ifstream& file) {
    int count = 0;
    while((file >> b[count].title >> b[count].author) && count != n-1) {
        count++;
    }
}

推荐阅读