std::字符串相关的错误及其处理,c++

std::string related errors and handling them, c++

本文关键字:处理 c++ 字符串 std 错误      更新时间:2023-10-16

好吧,这可能是一个愚蠢的问题,但我还是会继续问。

所以,我想知道,与std::string用法相关的所有可能的错误是什么?我知道一些,例如,在各种std::string函数中,在大于std::字符串大小的位置访问char。

在编程时,我应该记住哪些错误并进行检查?

有没有其他方法可以有效地进行以下操作?

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 );

我有一个程序,它需要数百次这样的检查,所以我想知道,每次都有另一种方法来做if(some_condition)。

您不需要列出整个类的每个错误案例;只需查找您使用的函数的文档,其中通常列出了前提条件。

例如,cppreference.com在std::string::erase上的页面。

如果i大于字符串长度,则抛出out_of_range异常

参考:-std::string::擦除

所以你总能抓住它!

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;
}