strstr函数与2015年相比不起作用

strstr function does not work vs 2015

本文关键字:不起作用 2015年 函数 strstr      更新时间:2023-10-16

因此,我必须引入一些名称(无论如何),并计算其中有多少个名称我可以找到子字符串"ana"。我不允许使用字符作为名称,我需要使用字符串。我写的代码非常简单,但strstr函数不起作用。

#include <iostream>
#include <string>
#include<stdio.h>

using namespace std;
void main()
{
    string name;
    string ana;
    int ok = 0;
    int nr = 0;
    ana = "ana";
    cout << "if you want to stop entering names introduce 1 after the last name, else introduce 0.";
    while (ok == 0)
    {
        cout << "Name here: " << flush;
        getline(cin, name);
        if (strstr(name, ana) != 0)
            nr++;
        cin >> ok;
    }
    cout << "The number of names that contain 'ana' is: " << nr;
}

你能帮我一下吗?错误为:"严重性代码描述项目文件行禁止显示状态错误C2665"strstr":2个重载都无法转换所有参数类型T1E1 e:\uni\an ii\lf\T1E1\T1E1\e1.cpp 20"

strstr适用于C字符串,而不是std::string

请改用std::string::find

代替

  if (strstr(name, ana) != 0)
        nr++;

使用

  if ( name.find(ana) != std::string::npos )
     nr++;

否则,您可以包含头文件cstring,其中包含strstr函数。在.cpp文件中添加以下代码。

#include <cstring>

更多详细信息,请访问cppreference.com.