0

Alright, it might be a stupid question, but I will go ahead and ask anyway.

So, I was wondering, what are all the possible errors associated with std::string usage ? I know a few, for example accessing char at location greater then the std::string size in various std::string functions.

While programming what errors should I keep in mind and place checks on ?

And is there an another way to do following for example, efficiently ?

std::string s("some string.");

int i = s.find ( "." );


if (  i != std::string::npos    &&  i + 3 < s.length (  )  ) // <<== this check is what I am talking about
    s.erase ( i + 3 );

I have a program, which requires hundreds of such checks, so I was wondering, there was an another way then to do if( some_condition ) each time.

3
  • 1
    put it in a function. Commented Aug 12, 2013 at 7:54
  • @LuchianGrigore that seems a better option. Commented Aug 12, 2013 at 9:31
  • @StudentX: So, did you get your answer? Commented Aug 14, 2013 at 10:08

2 Answers 2

2

You don't need to list every error case for the whole class; just look up the documentation for the functions that you use, which typically lists preconditions.

For example, cppreference.com's page on std::string::erase.

Sign up to request clarification or add additional context in comments.

Comments

0

If i greater than the string length, an out_of_range exception is thrown

Ref:- std::string::erase

So you can always catch it !

std::string s("some string.");
int i = s.find ( "." );

if (i != std::string::npos)
try 
{
   s.erase ( i + 3 );
}
catch (const std::out_of_range& err) 
{
  std::cerr << "Out of Range error: " << err.what() << std::endl;
}

3 Comments

But then, in this case, this approach might not be advisable if input strings with '.'s in arbitrary are perfectly legal and to be expected. If this situation indicates corrupted data or something like that, I agree that throwing the exception and handling it can indeed be the better way.
unfortunately that's doesn't make life easy :(
@StudentX well then in that case I'd suggest writing your own erase and which put boundary checking on the pos

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.