0

I'm attempting to trim the strings that I read in from a file. I read the string, trim it, then do my stuff with it. As I read through the file, I eventually reach the end, meaning the endpos+1 results in an out of range exception.

What would be the "best" way of handling this issue? Below is my trimming code.

size_t startpos = num.find_first_not_of(" ");
size_t endpos = num.find_last_not_of(" ");
num = num.substr(startpos, endpos-startpos+1); //out of range on final string read from file

My idea would be to use a try-catch block for it, but this seems very novice (I am one after all!)

Thanks!

George G
  • 61
  • 1
  • 8
  • 7
    No, don't use a try-catch block. That's Java-think. In C++, exceptions should not be used for control flow. There's not really enough code here to recommend a solution, but as a guess, after the call to `find_first_not_of`, check whether `startpos` is equal to `std::string::npos`. – Pete Becker Jul 20 '16 at 13:40
  • *My idea would be to use a try-catch block for it* -- No. For C++, exceptions are to be used for *exceptional* conditions, not for masking coding bugs. You get an exception in this case, you fix the bug that the exception detected, and not `try / catch` around it. – PaulMcKenzie Jul 20 '16 at 13:53
  • The exception you get here is not because you reach the end of your file, only the end of your string. You could work around this by checking if 'startpos' and 'endpos' both exist and are not equal to each other. – DrDonut Jul 20 '16 at 14:12

0 Answers0