繁体   English   中英

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

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

我看了其他的getline问题,但无法提出解决方案。 我将有一个格式如下的文件:

book
author
book
author
...

代码是将书名读取到book.name的结构中,然后是book.author的作者,但我得到的是书的空白,只有作者正在打印。 我知道它覆盖了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;
}

更新:现在也可以使用向量,虽然我无法像下面的答案那样使用它,但至少对于我目前的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;
}

你应该改变

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

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