查看string :: find中的字符串中是否有两个空格,这段代码中有一个错误?

时间:2015-05-21 22:58:53

标签: c++ string

我正在阅读string manipulations in C++。在那里,作者提出了一段代码,用于测试字符串中是否有两个空格

string text;
getline (cin, text);

string::size_type position = text.find (' ');
if (position != string::npos)
{
    if  (text.find (' ', position+1) != string::npos)
    {
       cout << "Contains at least two spaces!" << endl;
    }else
    {
       cout << "Contains less than two spaces!" << endl;
    }
}else
{
  cout << "Contains no spaces!" << endl;
}

作者声明上述代码中存在错误。但是我看不到它,代码看起来很好。我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

该网站的作者错了,该计划中没有错误。

他认为find的可选参数必须介于0和length-1之间。如果是这种情况,那么如果第一个空格是字符串的最后一个字符,则程序将失败,因为position将是length-1,因此position+1将是length },超出该范围。

但实际上,如果position参数太高,它只返回string::npos。所以没有问题。