getline(file,array) 没有移动到下一行
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);
我查看了其他 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);