C++ 如何逐字读取文件并将这些字分配给结构?
在我的项目中,我有一个.txt文件,该文件顶部有图书数量,然后用空格分隔图书标题和作者,例如:C++ 如何逐字读取文件并将这些字分配给结构?,c++,file,struct,ifstream,eof,C++,File,Struct,Ifstream,Eof,在我的项目中,我有一个.txt文件,该文件顶部有图书数量,然后用空格分隔图书标题和作者,例如: 1 Elementary_Particles Michel_Houllebecq 然后我有一个book对象的结构 struct book { string title; string author; }; 由于有多本书和多个作者,因此有一个包含这些图书对象的图书数组。我需要做的是逐字阅读,把书名分配给book.title,把作者分配给book.author。这就是我到目前为止所做的
1
Elementary_Particles Michel_Houllebecq
然后我有一个book对象的结构
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;
基本上,这只是第一个字。如何使第一个单词分配给book.title,下一个单词分配给book.author
谢谢您这段代码
while (file >> file_string) {
b[count].title = file_string;
b[count].author = file_string;
count++;
}
你读了一个单词,给标题和作者分配了相同的值,不要指望编译器猜到你的意图;)
一些额外的提示和想法:
,而是将输入操作放入循环条件中。您可以跳过中间字符串,直接读入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++;
}
}
显然,答案是一次读两个单词,例如:
while(file>>str1>>str2){b[count].title=str1;b[count].author=str2;count++;}
谢谢!所以文本文件实际上比作者和标题有更多的字段,它也有页码。那么,如何将文件输入字符串转换为int呢?我可以做文件>>std:::stoi(b[count].pages吗?文件>>b[count].pages
就足够了。它的工作原理就像您从std::cin
读取输入一样。
void getBookData(book* b, int n, ifstream& file) {
int count = 0;
while((file >> b[count].title >> b[count].author) && count != n-1) {
count++;
}
}