Как загрузить данные разных типов(string, int) с файла txt в вектор структур? Я новичок, сижу уже часов 9. Мне нужен код, просто описанием я не пойму,
C++ Вектор структур:
std::vector<Book>&books
//файле у меня данные: War and Peace
Leo Tolstoy
// 2011
struct Book {
std::string title = "No title";
std::string author = "No author";
int year = 0;
bool isAvailable = true;
};
void loadBooksFromFile(std::vector<Book>&
books,
const std::string& filename="books.txt") {
std::ifstream file(filename);
if (!file.is_open()) {
std::ifstream file(filename);
std::cout << "Ошибка открытия файла!" <<
std::endl;
return;
}
`std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
Book book;
if (iss >> std::quoted(book.title) >>
std::quoted(book.author) >> book.year) {
books.push_back(book);
} else {
std::cout << "Ошибка чтения!" <<
std::endl;
}
Ответы (2 шт):
Автор решения: Solt
→ Ссылка
Если в файле построчно лежат название, автор, год. То первый проход цикла считывает строку War and Peace далее по пробелам её нарезает на заголовок, автора и год. Очевидно, что 'Peace' не укладывается в int.
Автор решения: Den
→ Ссылка
Вы не разобрались как работает getline()
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <vector>
struct Book {
std::string title = "No title";
std::string author = "No author";
int year = 0;
bool isAvailable = true;
};
void loadBooksFromFile(std::vector<Book>& books, const std::string& filename = "../books.txt")
{
// проверка что такой файл существует и открыт для чтения
std::ifstream file(filename);
if (!file.is_open()) {
std::cout << "Ошибка открытия файла!" << std::endl;
return;
}
// чтение самого файла
std::string line;
int line_size_book(3), i(1);
Book book;
while (std::getline(file, line)) {
std::stringstream ss;
ss << std::quoted(line);
switch (i % line_size_book) {
case 0:
book.year = std::stoi(line);
books.push_back(book);
break;
case 1:
book.title = ss.str();
break;
case 2:
book.author = ss.str();
break;
default:
break;
}
i++;
}
file.close();
}
int main()
{
std::vector<Book> books;
loadBooksFromFile(books);
for (size_t i(0); i < books.size(); i++) {
std::cout << books[i].title << " : " << books[i].author << " " << books[i].year << std::endl;
}
}