当没有字符串匹配时,字符串中的查找函数输出垃圾

Find function in String outputs garbage when no string matches

我有以下代码:-

    string name = "hello world";
    size_t find = name.find("world");

    if (find != string::npos) {
        cout<<"match found at "<<find;
    }
    else{
        cout<<find;
    }

这个程序工作正常并按预期打印 6 个输出。

但是如果我把它改成size_t find = name.find('\n'); 它将垃圾值打印为 18446744073709551615。查找函数在找不到匹配的字符串时是否打印垃圾值??

引用自http://www.cplusplus.com/reference/string/string/find/

Return Value

The position of the first character of the first match. If no matches were found, the function returns string::npos.

size_t is an unsigned integral type (the same as member type string::size_type).

您的函数因此打印 std::string::npos,例如在 MSVS std 库实现中是

basic_string<_Elem, _Traits, _Alloc>::npos =
        (typename basic_string<_Elem, _Traits, _Alloc>::size_type)(-1);

您的 64 位系统上的最大无符号整数值是:18,446,744,073,709,551,615,参见 https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx

您可以将代码更改为

string name = "hello world";
size_t find = name.find("world");

if (find != string::npos) {
    cout<<"match found at "<<find;
}
else {
    cout<<"match not found";
}

更改您的 else 语句以打印 "not found"。

您的代码正在打印 find 中的 return 值,未找到时为 std::string::npos

It prints garbage value as 18446744073709551615. Does find function prints Garbage value when it does not find the matched string ??

不,std::string::find() 不打印。相反,您打印出它的 return 值。而且这不是垃圾值,只是 std::basic_string::npos.

的值

参见std::basic_string::npos的定义:

static const size_type npos = -1;

This is a special value equal to the maximum value representable by the type size_type.