Detect what words contain in the RECV

Hi,

I am doing a chat Server + Client,
when client reply "You are beautiful", server will detect the word "Beautiful", and then server will reply "Thanks You" to client chat,

below is the code of server receiving the "line" from client,
how can I detect if the line contains "beautiful" ?

while (recv(connectSocket, line, MAX_MSG, 0) > 0) {
cout << " -- " << line << "\n";
Given you print line with cout, I suspect it is NUL terminated. In that case, you can use the function strstr and check if it returns non-NULL, like so:

1
2
3
4
5
6
7
8
if(strstr(line, "beautiful"))
{
    //Thank the client
}
else
{
    //Don't thank the client
}


Note this is case-sensitive, you it will see Beautiful and beautiful as different inputs.
You can get over case-sensitivity by converting everything to upper or lowercase before checking...
http://www.cplusplus.com/reference/cctype/toupper/?kw=toupper

Nice one shadowwolf, I didn't know about strstr() I would have suggested converting to c++ string and using string.find();

While both ways are acceptable (and I'm personally more comfortable working with string rather than cstring), not having to convert the type is a definite win.
or you could use strstri which is not case sensitive...
Last edited on
What library is that function in? Strstri()?
its logic.. I was told if you want to compare 2 strings use strcmpi, surprisingly it works with strstri too :)

anyway

the library is Shlwapi.lib
strstri is not a standard function. strstr is part of the standard library and defined in <cstring> in C++. A lot of C libraries provide some implementation of a case-insensitive version of strstr, for example, windows provides the StrStrI function in Shwlwapi, like programmer007 said.

The problem is that if you need your solution to compile on other compilers, with other C runtimes, this function might not be available or have another name. For example, on Linux there's a GNU extension function called strcasestr, which does the same as strstr but case-insensitive. Considering we're on the forum part for Linux and Unix, that one is a bit more likely to work than strstri. It's just another platform using another name for the same function, even though no platform is required to even provide it according to the C++ standard.

The only truly platform independent way to do this is write the function yourself, which should not be too hard. You could just convert both strings to either lower or upper case using the standard tolower and toupper functions in <cctype>, and then use a regular strstr call to do the same. But if it does not matter what platforms your code should run on, you could try a function provided as an extension by your C rutnime.
Last edited on
didn't knew that... thanks

BTW can't we just load the library?
Topic archived. No new replies allowed.