Filestream
-
int main() { std::ifstream file("Account.txt"); std::map<std::string, std::string> accounts; std::string line; std::string id, pw; while (std::getline(file, line)) { std::stringstream buffer; buffer.str(line); buffer >> id; buffer >> pw; accounts.insert({ id, pw }); } for (auto account : accounts) { std::cout << account.first << " " << account.second << std::endl; } file.close(); system("pause"); return 0; }
Wie könnte man den Code verbessern?
Ich versuche aus einer Informationen herauszulesen und diese dann in einer Map zu speichern anschließend gebe ich die Informationen aus.
-
Wieso liest du eine Zeile vom Stream, packste die in einen anderen Stream und liest erst daraus dann die Daten, die du haben willst?
-
Du kannst den stringstream auch weglassen:
while (file >> id >> pw) accounts.insert({ id, pw });
Nachteil: Könnte schiefgehen wenn es pro Zeile mehr als zwei Strings gibt.
-
So dürfte es identisch sein:
while (file >> id >> pw) { accounts.insert({ id, pw }); file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
-
sebi707 schrieb:
So dürfte es identisch sein:
while (file >> id >> pw) { accounts.insert({ id, pw }); file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
Ists nicht, Bsp. "a\nb".
Die Variante des TE ist aber auch nicht ideal, "a b c" wird als "a"+"b" geparsed und "a" als "a"+"".