For simplicity, it lacks error handling. The std::stof throws exceptions when input is not acceptable. There are other ways too. There are two important things to do: (1) to learn to handle invalid input, and (2) to choose the general policy on what to do on error.
C++11 can declare auto to_float( const std::string& str ) -> float; that could look more intuitive (but is mainly for the compiler, which has no psychic abilities at all).
Text files are goofy things. I actually had an argument before with people about the number of lines in a text file.
I count newlines as separators, introducing a new line.
But some people (even some more modern systems) count them as line terminators. (Which is why your text files should always terminate with a newline.)
So you have to consider that the last line may be an empty line. If it is, discard it -- don't count it as one of your lines.
currently the script gets the last line, I get the previous line of the last
I showed you how to get the last line. I'm sure you can modify the code to make it work for the next-to-last if you really wanted to, although the next step would be to make it work for arbitrary lines in the file, and just reading in all the lines for that and retrieving them from a container would probably be preferred.
Duoas wrote:
So you have to consider that the last line may be an empty line.
The posted code ignores all empty lines (in >> std::ws prior to ignoreline.) So, I suppose it doesn't actually retrieve the last line in the file in some cases. Maybe getLastNonEmptyLine would be a better name for the function.
Something like this. I didn't compile it at all, but I use this basic model in my program and I read everything in a file. There could be more error handling.
This isn't the most efficient way, but it gets the job done. You could empty the vector if you want it a bit more conservative of memory.