Hi,

I want to assign a char pointer value to enmerated value, to use in a switch statement.
Given below is the code segment. I dont hv an idea how to convert and assign char pointer value to a enumerated value. Pls can someone help me to resolve this

enum IncomingTCPCommand
	{ 
		HEARTBEAT	=0x0000,
		PUBLISH		=0x0001,
		RETRIEVE	                =0x0002,
		SETSTATUS	=0x0003,
		GETCOUNT_V1	=0x0004,
};
char * p_chArrayMessage;
char * m_p_chCommandName ;
string p_szMessage = "0x0000,set";// input string
p_chArrayMessage = new char [p_szMessage.size()+1];//copy into a char array
strcpy (p_chArrayMessage, p_szMessage.c_str());
m_p_chCommandName = strtok(p_chArrayMessage, ",");get the first token

//problem starts from here
enum IncomingTCPCommand TCPCommand = m_p_chCommandName;	
	m_iCommandID = (int)TCPCommand;
					    
	switch(m_iCommandID)
	{
		case HEARTBEAT:					
		//TODO								case PUBLISH:
}

Recommended Answers

All 3 Replies

STL to the rescue.

#include <algorithm>
#include <cctype>  // since you are using char*

...

bool str_eq_ci( const char* a, const char* b )
  {
  for (; *a && *b; a++, b++)
    if (std::toupper( *a ) != std::toupper( *b )) return false;
  if (*a || *b) return false;
  return true;
  };

...

const char *IncomingTCPCommandStrings[] = {
  "heartbeat",
  "publish",
  ...
  };

// Convert string into index:
TCPCommand = std::find_if(
              IncomingTCPCommandStrings,
              IncomingTCPCommandStrings+NUM_OF_TCP_COMMANDS,
              str_eq_ci
              )
            - IncomingTCPComandStrings;

This, of course, is very simplistic. You would be better off playing with std::string.
Further, if your enums aren't sequential, you'll be better off using a std::map().

Hope this helps.

Hi Duaos,
Thankx 4 ur support. but frm ur solution i couldnt solve the problem. bcozz i hv to use enumeration. (cannot use char array of pointers like u introduce). could u pls tell me way of overcoming this issue by using enumerations as well

You are aware that my solution converts a string into an integer value compatible with your enum?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.