我正在阅读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;
}
作者声明上述代码中存在错误。但是我看不到它,代码看起来很好。我错过了什么吗?
答案 0 :(得分:4)
该网站的作者错了,该计划中没有错误。
他认为find
的可选参数必须介于0和length-1
之间。如果是这种情况,那么如果第一个空格是字符串的最后一个字符,则程序将失败,因为position
将是length-1
,因此position+1
将是length
},超出该范围。
但实际上,如果position
参数太高,它只返回string::npos
。所以没有问题。