我正在从文件和每一行读取数据结构,但是当我尝试打印该文件时,它并不总是有效。这是我从中读取的文件:
TuniLib;Sebesta;Programming Languages;14
Sampola;Budd;Data Structures in C++;2
Sampola;Wirth;Compiler Construction;on-the-shelf
Metso;Savitch;Problem Solving with C++;8
Sampola;Sebesta;Programming Languages;3
这是我的数据结构:
struct Book {
std::string title;
std::string author;
int reservations;
};
using BookVector = std::vector<Book>;
using AuthorData = std::map<std::string, BookVector>;
using Libaries = std::map<std::string, AuthorData>;
const int ON_THE_SHELF = 0;
这是我的代码:
//prints the libaries
void print_libaries(const Libaries& libs) {
for (auto libinfo: libs) {
std::cout << libinfo.first << std::endl;
}
}
//Adds the information to Libaries structure
void insert_book(Libaries& libs, const std::string& libary, const std::string& author,
const std::string& bookname, int reservations) {
if (libs.find(libary) == libs.end()) {
libs.insert({libary, {}});
}
if(libs.at(libary).find(author) == libs.at(libary).end()) {
libs.at(libary).insert({author, {}});
}
for (Book& book: libs.at(libary).at(author)) {
if (book.title == bookname) {
book.reservations = reservations;
return;
}
}
libs.at(libary).at(author).push_back({bookname, author, reservations});
}
//reads the information and splits the information
void read_file(std::ifstream& stream) {
Libaries libs;
int i;
std::vector<std::string> parts;
std::string line;
while (getline(stream, line)) {
parts = split(line, ';');
if (parts.at(3) == "on-the-shelf") {
i = ON_THE_SHELF;
} else {
i = std::stoi(parts.at(3));
}
insert_book(libs, parts.at(0), parts.at(1), parts.at(2), i);
}
for (auto libinfo: libs) {
std::cout << libinfo.first << std::endl;
}
}
int main() {
Libaries libs;
std::string file_name;
std::cout << "Input file: ";
std::getline(std::cin, file_name);
std::ifstream file(file_name);
if (not file) {
std::cout << "Error: the input file cannot be opened." << std::endl;
return EXIT_FAILURE;
}
read_file(file);
while(true) {
std::string command ;
std::cout << "> ";
std::getline(std::cin, command);
if (command == "libaries") {
std::cout << "test"<< std::endl;
print_libaries(libs);
}
}
}
因此这是程序不会在print_libaries
函数中打印库。仅当我在read_file
函数中尝试时才打印它们。我认为我的结构某种程度上不记得键和值,或者它们从我的结构中删除了,但我不知道为什么。
这里也是我的拆分功能,以防万一:
std::vector<std::string> split(const std::string& s, const char delimiter, bool ignore_empty = false){
std::vector<std::string> result;
std::string tmp = s;
while(tmp.find(delimiter) != std::string::npos)
{
std::string new_part = tmp.substr(0, tmp.find(delimiter));
tmp = tmp.substr(tmp.find(delimiter)+1, tmp.size());
if(not (ignore_empty and new_part.empty()))
{
result.push_back(new_part);
}
}
if(not (ignore_empty and tmp.empty()))
{
result.push_back(tmp);
}
return result;
}
如果有人可以帮助我,将不胜感激。