3 ms·
How does getline handle the out-of-memory condition? How do I avoid leaking memory – is that handled by std::string's RAII destructor? To detect the end-of-file
by wizzwizz4 4y ago
How does getline handle the out-of-memory condition? How do I avoid leaking memory – is that handled by std::string's RAII destructor? To detect the end-of-file condition, there's something about a failbit, but I'm only four pages of documentation in, so I don't know what that is yet.
What would the equivalent code look like in C++, handling EOF and OOM conditions appropriately?
- blackpill0w 4y agoprobably std::string would throw std::bad_alloc, and there is also the failbit flag which std::getline sets
- zabzonk 4y agoif memory is exhausted, then getline throws a bad_alloc exception. if end of fileis reached (which i am not sure your code deals with correctly) then getline returns a stream in a bad state. so something in outline like this (syntactically correct. std:: omitted for brevity, but probably not what you would really write): string input; try { if ( cin.getline ( input ) ) { // ok read input, do something with it } else { // some sort of predictable error - look at state of cin to diagnose EOF } } catch (...) { /// something terrible happened - as hard to recover as it would be in c }