C++ 当没有字符串匹配时,字符串中的Find函数输出垃圾

C++ 当没有字符串匹配时,字符串中的Find函数输出垃圾,c++,string,function,output,C++,String,Function,Output,我有以下代码:- string name = "hello world"; size_t find = name.find("world"); if (find != string::npos) { cout<<"match found at "<<find; } else{ cout<<find; } string name=“hello world”; size\u t f

我有以下代码:-

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

    if (find != string::npos) {
        cout<<"match found at "<<find;
    }
    else{
        cout<<find;
    }
string name=“hello world”;
size\u t find=name.find(“世界”);
if(find!=string::npos){
不能引用

返回值

第一个匹配的第一个字符的位置。 如果未找到匹配项,函数将返回字符串::npos。

size_t是无符号整数类型(与成员类型相同 字符串::大小(类型)

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

basic_string<_Elem, _Traits, _Alloc>::npos =
        (typename basic_string<_Elem, _Traits, _Alloc>::size_type)(-1);
basic_字符串::npos=
(typename基本字符串::大小类型)(-1);
这是64位系统上的最大无符号整数值:18446744073709551615,请参阅

您可以将代码更改为

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

if (find != string::npos) {
    cout<<"match found at "<<find;
}
else {
    cout<<"match not found";
}
string name=“hello world”;
size\u t find=name.find(“世界”);
if(find!=string::npos){

无法将else语句更改为打印“未找到”

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

它将垃圾值打印为18446744073709551615。当找不到匹配字符串时,find函数是否打印垃圾值

不,
std::string::find()
不打印。而是打印它的返回值。它不是垃圾值,只是
std::basic_string::npos
的值

见以下定义:

这是一个特殊值,等于类型
size\u type
可表示的最大值


该值不是“垃圾”--它是
string::npos
。saved my day:)
static const size_type npos = -1;