【问题标题】:String At function run time error字符串在函数运行时错误
【发布时间】:2011-08-08 20:48:31
【问题描述】:

这是创建运行时错误“Microsoft Visual C++ 运行时库”http://www.flickr.com/photos/66130188@N07/6023459646/的代码的 sn-p

string text = something;
size_t index = text.find("hoopla");
try{
    if(text.at(index-1)<'0'&&text.at(index-1)>'9')
       return false;
}catch(out_of_range){return true;}

我在 Qt creator 中运行它。它没有触发 catch 块。当程序到达 text.at(index-1) 并且 index-1 超出范围时,它会在 Qt 中创建运行时错误http://www.flickr.com/photos/66130188@N07/6023453724/

我在使用 MVS2010 时没有遇到问题。有什么建议吗?

【问题讨论】:

  • (没关系。我发现你并没有真正在 Qt 中编码。)
  • @Daniel R Hicks 我在 Qt C++ 项目中使用 C++ 对象。

标签: c++ string function qt-creator


【解决方案1】:

您可以完全避免异常检查,只需先检查find的返回值:

if ((index == std::string::npos || index == 0)        ||
    (text[index - 1] < '0' && text[index - 1] > '9')    )
{
  return false;
}

在第一种情况下,npos,没有找到搜索字符串,而在第二种情况下,它位于环境字符串的开头,因此您无法查看它之前的字符。

(这被称为“攻击性编程”:不要在运行时检查错误,而是构造你的算法,以便你知道你的访问是正确的。如果你愿意,你可以添加一个断言 assert(index &lt; text.length()); 表示您确定您持有正确的值,这不会影响您的发布版本。)

更新:.at() 替换为 [],因为我们对自己很有信心。

【讨论】:

  • cplusplus.com/reference/string/string/at 所述:If the position passed is past the end of str, an out_of_range exception is thrown.
  • @vines:这跟我的回答有什么关系?
  • 但是传递的位置不是“超过 str 的末尾”,而是负数。
  • 是负数还是无符号大值?
  • string::at(size_t),其中 size_t (显然)是无符号的。 @Kerrek SB:它必须做到以下几点:为什么(据说)它应该在哪里没有例外?
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 2016-02-01
  • 2020-02-18
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多