0
#include <iostream>
using namespace std;
int main ()
{
    char name[10];
    cin>>name;
    char str[] = "Thomas";
    char * pch;
    pch=strchr(name,str);
    if (pch!=NULL) {
        cout<<"Foud"<<endl;
    }

    return 0;
}

Hello, why i can't use 2 variables in strchr function, if you know how to search words in string

Eduard Wirch
  • 9,785
  • 9
  • 61
  • 73
Wizard
  • 10,985
  • 38
  • 91
  • 165
  • Have you considered that perhaps you are looking at the wrong tool for the job? – Jan Hudec Dec 19 '11 at 13:54
  • why is this tagged C++ when it is using mostly the C way of doing things? either use `std::string` or remove cout and use C, but don't try ugly mixing – PlasmaHH Dec 19 '11 at 14:34

3 Answers3

4

Use strstr

#include <iostream>
using namespace std;
int main ()
{
    char name[10];
    cin>>name;
    char str[] = "Thomas";
    char * pch;
    pch=strstr(name,str);
    if (pch!=NULL) {
        cout<<"Found"<<endl;
    }

    return 0;
}
sehe
  • 374,641
  • 47
  • 450
  • 633
2

The second argument to strchr is a character, expressed as an int. It will find the first instance of that character in the string.

char *strchr(const char *s, int c);

If you want to find a substring in a string use strstr,

char *strstr(const char *haystack, const char *needle);

strstr will point to the first substring or NULL if it's not found.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
1

strchr is used to Locate first occurrence of character in string. strstr is used for Locate substring. See the references:

So, your program should look like:

#include <iostream>

using namespace std;

int main ()
{
    char name[10];
    cin>>name;
    char str[] = "Thomas";
    char *pch = strstr(name,str);
    if (pch != NULL) {
        cout<<"Found"<<endl;
    }

    return 0;
}
Jomoos
  • 12,823
  • 10
  • 55
  • 92