|
<blockquote class="FQ"><div class="FQA">Comp_User wrote:</div>is there another alternative to achieving the same result?</blockquote>
Not without some bit of programming.
I often use a std::map (I've used the Boost Assign[^] library as well, as it makes container so much easier and Boost Optional[^] to provide for the case when no enumerals match the string) like this:
#include <map>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/optional.hpp>
enum XX { AA, BB, CC, DD, EE };
boost::optional<XX> XXFromString(std::string const& s)
{
#define ITEM(I) (#I, I)
const std::map<std::string, XX> MapStringToXX = boost::assign::map_list_of ITEM(AA)ITEM(BB)ITEM(CC)ITEM(DD)ITEM(EE);
#undef ITEM
std::map<std::string, XX>::const_iterator itEnum = MapStringToXX.find(s);
return (itEnum == MapStringToXX.end())?boost::optional<XX>():itEnum->second;
}
I've used the ITEM macro so I only have to type enumerals once - the macro expands to a string of the enum and a token of the enumeral.
|
|
|
|
|
Stuart,
I am not allowed to use any additional library like the Boost Assign library that you have made use of.
could you please give me a simpler example to demonstrate as to how you achieve the conversion?
Thanks.
|
|
|
|
|
You may do something similar to the following:
enum.txt file
ENUM(ONE)
ENUM(TWO)
ENUM(THREE)
ENUM(FOUR)
source code
#define ENUM(s) s,
enum Numbers
{
#include "enum.h"
NUMBERS
};
#undef ENUM
int stringtonumber(char * str)
{
#define ENUM(s) #s,
static char * tok[NUMBERS+1] =
{
#include "enum.txt"
NULL
};
#undef ENUM
int i=0;
while ( tok[i] )
{
if ( ! strcmp(tok[i],str ) )
return (i+1);
i++;
}
return -1;
}
void main()
{
printf("%s is %d\n", "THREE", stringtonumber("THREE"));
}
The sample code is silly, but you possibly got the idea.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
OK - just using std::map (I presume you're allowed to use the C++ standard libraries?):
enum XX { AA=1, BB, CC, DD, EE };
std::pair<bool, XX> FromString(std::string const& s)
{
static std::map<std::string, XX> MapStringToXX;
if (MapStringToXX.empty())
{
#define INSERT_ITEM(I) MapStringToXX.insert(std::make_pair(std::string(#I), I))
INSERT_ITEM(AA);
INSERT_ITEM(BB);
INSERT_ITEM(CC);
INSERT_ITEM(DD);
INSERT_ITEM(EE);
}
#undef ITEM
std::map<std::string, XX>::const_iterator itEnum = MapStringToXX.find(s);
return (itEnum == MapStringToXX.end())
?std::make_pair(false, XX())
:std::make_pair(true, itEnum->second);
}
This time, the map is a static variable that you initialise the frist time the function is called, while we return a (bool, XX) pair, using the bool item to show if the string was found or not.
Warning: this code isn't going to be thread-safe...
|
|
|
|
|
Comp_User wrote: static void ConvertStrtoEnum(TCHAR &szEnum, int myenum)
{
if(!_tcscmp(szEnum, _T("ZERO"))
myenum = ZERO;
else if(!_tcscmp(szEnum, _T("ONE"))
myenum = ONE;
.
.
.//Do the same for all enum values.
Instead of this, I suggest you to store the strings in an array and iterate... then the index can be used as corresponding enumID.
For eg.,
int GetIdx( LPCTSTR lpctszID )
{
const MAX_IDS = 3;
LPCTSTR strRef[MAX_IDS]={ _T( "ONE" ), _T( "TWO" ), _T( "THREE" ) };
for(int nIdx = 0; nIdx < MAX_IDS; nIdx++)
{
if( 0 == lstrcmp( lpctszID, strRef[nIdx] ))
{
return nIdx;
}
}
return -1;
}
But if the enum is not sequential then there needs another similar method to iterate the enum ID.
- ns ami -
|
|
|
|
|
Dear all,
I have a C++ unmanaged COM object which is being used in a C## application.
Sometimes, when I raise event from COM object I get an HRESULT with below message:
The process cannot access the file because it is being used by another process.
I can not understand how this message relates to event raising.
Please help me about this weird situation If you have similar experience.
Regards
|
|
|
|
|
Hi all
i am geting error
Unhandled exception at 0x00529f01 in DemoUSB.exe: 0xC0000005: Access violation reading location 0x00000000. . and application creash at this point
ATL_NOINLINE void Fork( __in int nLength )
{
CStringData* pOldData = GetData();
int nOldLength = pOldData->nDataLength;
CStringData* pNewData = pOldData->pStringMgr->Clone()->Allocate( nLength, sizeof( XCHAR ) );
if( pNewData == NULL )
{
ThrowMemoryException();
}
When i debug the code then i am not geting any exception but application run regular then exception generated.
Plz help me
|
|
|
|
|
The message "Access violation reading location 0x00000000." means that you are accessing a pointer variable without assigning a memory.
Could you please check the pointers in CStringData* pOldData = GetData(); and CStringData* pNewData = pOldData->pStringMgr->Clone()->Allocate( nLength, sizeof( XCHAR ) ); lines.
( My suggestion is to check all pointers in CStringData* pNewData = pOldData->pStringMgr->Clone()->Allocate( nLength, sizeof( XCHAR ) ); )
In the debug mode, debugger is allocating and controlling memory access. If you use an unallocated pointer, the output will be undefined. Sometimes it will show exception/assertion or sometimes works fine. So it's better to check the pointers before use.
aks
|
|
|
|
|
Hi friends,
We have two applications . one is OLE container and another is OLE server application. It was built with 2005 and old MFC classes such as CWinApp, CFrameWnd and CToolbar classes. It was working fine. We were able to embed the server application in container application.
We have migrated the application to 2008 . Now we are using new MFC feature pack classes CWinAppEx,CFrameWndEx and CMFCToolbar. Individually, both application are working fine. But we are not able to embed the server application in container application.
Can anyone provide the solution on this ? any sample application avialable for OLE server - container with VS2008 MFC feature pack classes.
|
|
|
|
|
Hi All,
I got a link error while compiling my project.The error is in another module ie in another .obj .This is static link library.Can anyone help me to find a solution .The error is given below.
error LNK2019: unresolved external symbol "__declspec(dllimport) public: __cdecl std::basic_string<char,struct>,class std::allocator<char> >::basic_string<char,struct>,class std::allocator<char> >(class std::basic_string<char,struct>,class std::allocator<char> > const &)" (__imp_??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAA@AEBV01@@Z) referenced in function "public: __cdecl std::logic_error::logic_error(class std::basic_string<char,struct>,class std::allocator<char> > const &)"
Thanks & Regards
VIJITH VIJAYAN
|
|
|
|
|
1. Are you sure that your application linked with proper lib
2. Are you using any third party libraries like STL Port or something? then make sure you've put it in the right include order
-Sarath.
"Great hopes make everything great possible" - Benjamin Franklin
|
|
|
|
|
yes i had linked .And thanks for the quick reply
Thanks & Regards
VIJITH VIJAYAN
|
|
|
|
|
Hi all,
I m using Killfoucus function for button control but its not working.
i add this from Control events of Button control BN_KILLFOCUS.
please tell me what can i do for this.
thanks in advance.
To accomplish great things, we must not only act, but also dream;
not only plan, but also believe.
|
|
|
|
|
Is your button having BS_NOTIFY style? You can set this style in the resource editor, if you are using it (Properties > Styles > Notify).
- ns ami -
|
|
|
|
|
Thanks its done.
To accomplish great things, we must not only act, but also dream;
not only plan, but also believe.
|
|
|
|
|
You are welcome...
- ns ami -
|
|
|
|
|
Create a button class, say CButtonEx, derived from CButton and map the ON_WM_KILLFOCUS message.
Change the class of the button control that you have to CButtonEx.
aks
|
|
|
|
|
Hi All,
In my MFC application,iam getting the values from equipment.It returns the string value with special character like READ with special character.That value is 0x17.
How to remove that special character in CString?
Pls help me..............
Thanks & Regards,
Anitha
|
|
|
|
|
You can use Remove()
See this[^]
- ns ami -
|
|
|
|
|
Hi,
how can i detect if the LAN cable is unlplugged, can i check the status of the connection?
what is the maximum number of sockets i can use in one application.
Thanks..
pramod
|
|
|
|
|
|
- how can i detect if the LAN cable is unlplugged, can i check the status of the connection?
try IsNetworkAlive() API
aks
|
|
|
|
|
There are alot of ways of determining the status of a network connection! All of the functions below will tell you the status of a network connection. Microsoft has provided us with many alternatives.
You could also use the IP Helper[^] tools to query the status something like this:
#include "Iphlpapi.h"
#pragma comment(lib, "iphlpapi.lib")
VOID PrintOperationalEthernet()
{
BYTE *pBuf=NULL;
DWORD dwSize=0;
DWORD dwResult=0;
BOOL bConnected=FALSE;
PMIB_IFTABLE pMIBTable;
CString str;
GetIfTable(NULL,&dwSize,FALSE);
pBuf=new BYTE[dwSize];
pMIBTable=reinterpret_cast<PMIB_IFTABLE>(pBuf);
if(NO_ERROR == GetIfTable(pMIBTable,&dwSize,FALSE))
{
for(UINT i=0; i < pMIBTable->dwNumEntries; ++i)
{
if(MIB_IF_TYPE_ETHERNET == pMIBTable->table[i].dwType)
{
bConnected = MIB_IF_OPER_STATUS_OPERATIONAL == pMIBTable->table[i].dwOperStatus;
char szBuf[MAX_PATH];
sprintf(szBuf,"%s is %s\n",pMIBTable->table[i].bDescr,
TRUE == bConnected?"Connected":"Offline");
TRACE(szBuf);
}
}
}
delete []pBuf;
}
You could also use the lower level DeviceIOControl[^] to query the device status directly from the network card like this:
#include <winioctl.h>
typedef ULONG NDIS_OID, *PNDIS_OID;
#define _NDIS_CONTROL_CODE(request,method) CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD, request, method, FILE_ANY_ACCESS)
#define IOCTL_NDIS_QUERY_GLOBAL_STATS _NDIS_CONTROL_CODE(0,METHOD_OUT_DIRECT)
#define OID_GEN_MEDIA_CONNECT_STATUS 0x00010114
typedef enum _NDIS_MEDIA_STATE
{
NdisMediaStateConnected,
NdisMediaStateDisconnected
} NDIS_MEDIA_STATE,*PNDIS_MEDIA_STATE;
VOID PrintOperationalEthernet()
{
int index =0;
DWORD dwType =0;
HKEY key;
HKEY cardkey;
CString str;
HANDLE hDevice;
NDIS_OID OidCode = OID_GEN_MEDIA_CONNECT_STATUS;
ULONG status=0;
ULONG dwRet=0;
TCHAR szCardVal[CHAR_MAX];
TCHAR szDescription[MAX_PATH];
TCHAR szDevice[MAX_PATH];
str.Format(_T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards\\"));
if(ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE,str,&key))
{
while(ERROR_SUCCESS == RegEnumKey(key,index++,szCardVal,CHAR_MAX))
{
str.Format(_T("%s\\%d"),str,_ttoi(szCardVal));
if(ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE,str,&cardkey))
{
str = str.Left(str.ReverseFind('\\'));
DWORD dwLen = CHAR_MAX * sizeof(TCHAR);
if(ERROR_SUCCESS == RegQueryValueEx(cardkey,_T("ServiceName"),NULL,
&dwType,(LPBYTE)szCardVal,&dwLen))
{
RegQueryValueEx(cardkey,_T("Description"),NULL,
&dwType,(LPBYTE)szDescription,&dwLen);
_stprintf(szDevice,_T("\\\\.\\%s"),szCardVal);
hDevice = CreateFile(szDevice,GENERIC_READ,FILE_SHARE_READ|
FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
if(DeviceIoControl(hDevice,IOCTL_NDIS_QUERY_GLOBAL_STATS,
&OidCode,sizeof(NDIS_OID),&status,
sizeof(ULONG),&dwRet,NULL))
{
TCHAR szBuf[MAX_PATH];
_stprintf(szBuf,_T("%s is %s\n"),szCardVal,
NdisMediaStateConnected == status?_T("Connected"):_T("Offline"));
TRACE(szBuf);
CloseHandle(hDevice);
}
RegCloseKey(cardkey);
}
}
}
RegCloseKey(key);
}
}
You could also use the Internet Connection Firewall API[^] to determine the status of the network card such as below:
#include <netcon.h>
#define _WIN32_DCOM 1
typedef void(__stdcall *LPNcFreeNetconProperties)(NETCON_PROPERTIES *pProps);
VOID PrintOperationalEthernet()
{
HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IDENTIFY,
NULL, EOAC_NONE, 0
);
HMODULE hmod=LoadLibrary(_T("netshell.dll"));
if(hmod)
{
LPNcFreeNetconProperties NcFreeNetconProperties=(LPNcFreeNetconProperties)\
GetProcAddress(hmod,"NcFreeNetconProperties");
INetConnectionManager *pMan=0;
HRESULT hres=CoCreateInstance(CLSID_ConnectionManager,0,CLSCTX_ALL,\
__uuidof(INetConnectionManager),(void **) &pMan);
if(SUCCEEDED(hres))
{
IEnumNetConnection *pEnum=0;
HRESULT hres=pMan->EnumConnections(NCME_DEFAULT,&pEnum);
if(SUCCEEDED(hres))
{
INetConnection *pCon=0;
ULONG count;
bool done=FALSE;
while(pEnum->Next(1,&pCon,&count) == S_OK && !done)
{
NETCON_PROPERTIES *pProps=0;
hres=pCon->GetProperties(&pProps);
if(SUCCEEDED(hres))
{
wchar_t wszBuf[MAX_PATH];
wsprintf(wszBuf,_T("%s is %s\n"),pProps->pszwName,
NCS_CONNECTED == pProps->Status?_T("Connected"):_T("Offline"));
TRACE(wszBuf);
NcFreeNetconProperties(pProps);
}
pCon->Release();
}
pEnum->Release();
}
pMan->Release();
}
FreeLibrary(hmod);
}
CoUninitialize();
}
As was previously mentioned the WMI Win32_NetworkAdapter Class[^] can be used to determine device state by checking the NetConnectionStatus member. Sorry... no WMI sample... I absolutely hate WMI.
Best Wishes,
David Delaune
|
|
|
|
|
If you've just typed all that, I'm impressed! (And skeptical!)
Good little batches of code.
Iain.
Codeproject MVP for C++, I can't believe it's for my lounge posts...
|
|
|
|
|
Iain Clarke wrote:
If you've just typed all that, I'm impressed!
I actually created all three functions last night specifically for the reply. I typed them in VC2008 and then pasted them here. It is easier with intellisense and guarantees that the code is correct and compiles.
Best Wishes,
-David Delaune
|
|
|
|
|