strstr function does not work vs 2015

So, I have to introduce some names (it doesn't matter how) and count in how many of them I can find the substring 'ana'. I am not allowed to use char for the names, i need to use string. I wrote the code as simple as i could've thought but my strstr function does not work.

#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;
}

Can you please give me some help? The error is: "Severity Code Description Project File Line Suppression State Error C2665 'strstr': none of the 2 overloads could convert all the argument types T1E1 e:\uni\an ii\lf\t1e1\t1e1\e1.cpp 20 "

Upvotes: 1

Views: 727

Answers (2)

huoyao
huoyao

Reputation: 121

Otherwise, you can include the header file cstring which included strstr function. Add the following code in your .cpp file.

#include <cstring>

More details at cppreference.com.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206747

strstr works with C strings, not std::string.

Use std::string::find instead.

Instead of

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

use

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

Upvotes: 9

Related Questions