【问题标题】:Find function in String outputs garbage when no string matches当没有字符串匹配时,字符串中的查找函数会输出垃圾
【发布时间】:2016-09-25 09:51:17
【问题描述】:

我有以下代码:-

    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。 find 函数在找不到匹配的字符串时是否打印垃圾值??

【问题讨论】:

  • 值不是“垃圾”——它是string::npos

标签: c++ string function output


【解决方案1】:

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

返回值

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

size_t 是无符号整数类型(与成员类型相同 string::size_type)。

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

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

在您的 64 位系统上,最大 unsigned int 值是: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";
}

【讨论】:

    【解决方案2】:

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

    不,std::string::find() 不打印。相反,您正在打印它的返回值。而且不是垃圾值,只是std::basic_string::npos的值。

    std::basic_string::npos的定义:

    static const size_type npos = -1;
    

    这是一个特殊值,等于size_type 类型可表示的最大值。

    【讨论】:

    • 拯救了我的一天 :)
    【解决方案3】:

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

    您的代码正在打印来自find 的返回值,当找不到时为std::string::npos

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多