簡體   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