【问题标题】:strstr function does not work vs 2015strstr 函数与 2015 相比不起作用
【发布时间】:2016-01-04 07:28:40
【问题描述】:

所以,我必须介绍一些名称(不管如何),并计算其中有多少我能找到子字符串“ana”。我不允许使用 char 作为名称,我需要使用字符串。我写的代码尽可能简单,但我的 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 "

【问题讨论】:

  • 你不能直接分配字符串变量..使用 strcpy 或 memcpy 分配我说的是变量 ana
  • @Grv 可以,这是 C++ 和 std::string
  • @molbdnilo 好的..谢谢..

标签: c++ string function visual-studio-2015


【解决方案1】:

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

请改用std::string::find

代替

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

使用

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

【讨论】:

  • 另一种选择是将std::string 更改为char[] 并使用C 字符串
  • 呃,为什么这还能编译?编辑:啊,当然它不编译!这条路让我觉得这是一个 ICE
【解决方案2】:

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

#include <cstring>

更多详情请访问cppreference.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 2018-01-25
    • 2016-11-05
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多