例1:得到devicetype的值,首先原始字符串中是否包含devicetype=,如果包含此串儿则使用如下方式获得devicetype的值。
int main(int argc, char argv[])
{
string szMsg("_Community=public&_MachineName=192.168.6.96&_Port=161&devicetype=_SnmpWin&seid=2");
char *pPos = strstr(szMsg.c_str(), "devicetype=");
if(pPos)
{
char *chDevID = new char[strlen(pPos)];
if(chDevID)
{
memset(chDevID, 0, strlen(pPos));
cout << pPos << endl;
sscanf(pPos, "devicetype= %[^&]", chDevID);
cout << "Device Type is:" << chDevID << endl;
delete []chDevID;
}
}
{
string szMsg("_Community=public&_MachineName=192.168.6.96&_Port=161&devicetype=_SnmpWin&seid=2");
char *pPos = strstr(szMsg.c_str(), "devicetype=");
if(pPos)
{
char *chDevID = new char[strlen(pPos)];
if(chDevID)
{
memset(chDevID, 0, strlen(pPos));
cout << pPos << endl;
sscanf(pPos, "devicetype= %[^&]", chDevID);
cout << "Device Type is:" << chDevID << endl;
delete []chDevID;
}
}
}
例2:请自己比较两段代码运行结果有何不同。
#include <string>
#include <iostream>
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
string szMsg("0001A");
unsigned long ulValue = 0;
{
string szMsg("0001A");
unsigned long ulValue = 0;
sscanf(szMsg.c_str(), "%4x", &ulValue);
cout << ulValue << endl;
return 0;
}
cout << ulValue << endl;
return 0;
}
#include <string>
#include <iostream>
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
string szMsg("0001A");
unsigned long ulValue = 0;
{
string szMsg("0001A");
unsigned long ulValue = 0;
sscanf(szMsg.c_str(), "%x", &ulValue);
cout << ulValue << endl;
return 0;
}
cout << ulValue << endl;
return 0;
}
例3:还是让运行结果说话。
#include <string>
#include <iostream>
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
string szMsg("1000ABCD");
char szID[32] = {0};
{
string szMsg("1000ABCD");
char szID[32] = {0};
sscanf(szMsg.c_str(), "%[0-9]", szID);
cout << szID << endl;
return 0;
}
cout << szID << endl;
return 0;
}
还有一些有趣的例子有时间补上。