string.find()在c ++中找不到任何内容时不返回-1

时间:2017-03-25 21:03:23

标签: c++ string find

我是学生学习c ++并使用geany和namespace std。 我有一些代码让我遇到有关string.find()的问题,当我希望它返回-1时,它会因某种原因返回大数字。

string sentence [100];
cout << "Enter a sentence: \n";

for (int i=0; i<5; i++)
{
    cin >> sentence [i];
    if (sentence[i].find ('-') >0)
    {
        hyphenated ++;
        cout << "found a hyphen at "<< sentence[i].find('-') << " in word " << i << endl;
    }

}

当我输入带连字符的单词时,它返回正确的索引,但是当我输入不带连字符的单词时,我得到这个数字:18446744073709551615

感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

当找不到字符串或字符时,

std::string::find(...)及其姐妹函数不返回-1。他们返回std::string::npos

您应该检查std::string::findstd::string::npos的返回值,以断言您的查找成功。

for (int i=0; i<5; i++)
{
    cin >> sentence [i];
    auto pos = sentence[i].find('-');
    if (pos == std::string::npos)
    {
        hyphenated ++;
        cout << "found a hyphen at "<< pos << " in word " << i << endl;
    }

}

技术std::string::npos static const成员std::string::size_type定义为-1,但由于-1已转换为无符号类型,该值成为可以表示

的最大正整数std::string::size_type

答案 1 :(得分:0)

当找不到字符时,它返回string :: npos,一个常量,而不是C ++中的-1。

以下是相关文档:http://www.cplusplus.com/reference/string/string/find/