3 ms·
or in c++, simply call getline? i haven't traced thru your code, but i would not be surprised if there were errors in it, having written similar stuff myself.
by zabzonk 4y ago
or in c++, simply call getline? i haven't traced thru your code, but i would not be surprised if there were errors in it, having written similar stuff myself.
compare with using std::string and std::getline - easy to use and battle-hardened.
- wizzwizz4 4y agoHow 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 }
- johndough 4y agoJust to clearify: Do you make the assumption that the input only consists of a single line?
- zabzonk 4y agothat was my intention, but in the case of multiple lines c++ is evrn easier than in c - just use std::vector <std::string>.