sscanf详解(二)

来源:互联网 发布:win7软件字体模糊 编辑:程序博客网 时间:2024/06/05 08:47


几个常用例子


例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;
}
}

}

例2:请自己比较两段代码运行结果有何不同。

#i nclude <string>
#i nclude <iostream>

using namespace std;

int main(int argc, char * argv[])
{
string szMsg("0001A");
unsigned long ulValue = 0;

sscanf(szMsg.c_str(), "%4x", &ulValue);
cout << ulValue << endl;
return 0;
}

#i nclude <string>
#i nclude <iostream>

using namespace std;

int main(int argc, char * argv[])
{
string szMsg("0001A");
unsigned long ulValue = 0;

sscanf(szMsg.c_str(), "%x", &ulValue);
cout << ulValue << endl;
return 0;
}

例3:还是让运行结果说话。

#i nclude <string>
#i nclude <iostream>

using namespace std;

int main(int argc, char * argv[])
{
string szMsg("1000ABCD");
char szID[32] asccxzxcc {0};

sscanf(szMsg.c_str(), "%[0-9]", szID);
cout << szID << endl;
return 0;
}

原创粉丝点击