find() function not working
Sep 5, 2011 at 8:39pm UTC
So I'm having trouble understanding why the find() function isn't working. I am getting the error "Member reference base type 'char *' is not a structure or union" on the find function. I am also getting the error "Use of undeclared identifier 'npos'". Thank you for your help in advanced. Here is my code:
1 2 3 4 5 6 7
recv(sockfd, &buf, 256, 0);
cout << buf << endl;
char ping[] = "PING " ;
if (buf.find(ping) != npos)
{
//whatever happens
}
Sep 5, 2011 at 8:50pm UTC
You need to use
find()
on a
std::string
, not on a
char *
. Also, you should only pass in
buf
, to the
recv
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <string>
#include <iostream>
using namespace std;
{
char buf[256];
recv( sockfd, buf, 256, 0 );
string bufAsString( buf );
cout << bufAsString << endl;
char ping[] = "PING " ;
if ( bufAsString.find(ping) != npos )
{
//whatever happens
}
}
Sep 5, 2011 at 9:25pm UTC
Thank you so much that was very helpful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <string>
#include <iostream>
using namespace std;
{
static const size_t npos = -1; //Added cause npos was not declared
char buf[256];
recv( sockfd, buf, 256, 0 );
string bufAsString( buf );
cout << bufAsString << endl;
char ping[] = "PING " ;
if ( bufAsString.find(ping) != npos )
{
//whatever happens
}
}
Sep 5, 2011 at 10:26pm UTC
If npos
is still not declared, try string::npos
Topic archived. No new replies allowed.