简体   繁体   English

getline(文件,数组)没有移动到下一行

[英]getline(file,array) isn't moving to the next line

I've looked at the other getline questions and couldn't come up with a solution. 我看了其他的getline问题,但无法提出解决方案。 I will have a file formatted like so: 我将有一个格式如下的文件:

book
author
book
author
...

The code is to read the book title into the struct at book.name, and then the author at book.author but what I am getting is a blank for book and only author is printing. 代码是将书名读取到book.name的结构中,然后是book.author的作者,但我得到的是书的空白,只有作者正在打印。 I know it's overwriting book.name but I'm not sure how to remedy it. 我知道它覆盖了book.name,但我不确定如何解决它。

#include <string>
#include <fstream>
using namespace std;

struct Books {
   string name;
   string author;
};

Books books[100];


int main(){
   fstream file;
   file.open("test.txt");

   while(!file.eof()){
      getline(file,books[0].name);
      getline(file,books[0].author);
   }
   file.close();
   cout << books[0].name << " " << books[0].author << endl;

  return 0;
}

update: works with vectors now, too, though I've not been able to get it as fancy as the answer below, this is at least a bit more understandable for my level of C++ at the moment. 更新:现在也可以使用向量,虽然我无法像下面的答案那样使用它,但至少对于我目前的C ++级别来说这是可以理解的。

struct book_meta_data {
  string name;
  string author;
};
int i = 0;
book_meta_data b;
while ( getline(f,b.name) && getline(f,b.author) &&
      ++i){
        books.push_back(b);
      }

cout << books.size() << endl;
for (vector<int>::size_type i = 0; i != books.size(); i++){
  cout << books[i].name << " " << books[i].author << endl;
}

You should change 你应该改变

while(!file.eof()){
   getline(file,books[0].name);
   getline(file,books[0].author);
}

to

int i = 0;
while(getline(file,books[i].name) && getline(file,books[i].author) && ++i < 100);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM