今天在扫描字符串的时候出了一个让我意外的事情:
char *pStr = "[2,等待用户确认]"; int nRetCode = 0; char szError[64]={0}; if(2 == sscanf(pStr,"[%d,%s]",&nRetCode,szError)) { cout<<nRetCode <<" "<<szError<<endl; }
预期的结果当然是szError中保存的字符串不包含']'了,但是意外哈。
后百度了下,修改如下:
char *pStr = "[2,等待用户确认]"; int nRetCode = 0; char szError[64]={0}; if(2 == sscanf(pStr,"[%d,%[^]]s]",&nRetCode,szError)) { cout<<nRetCode <<" "<<szError<<endl; }
早知道sscanf用法有些繁琐,现在知道很实用。下面是百度的一个实例:
#include <iostream> using namespace std; int main(int argc, char *argv[]) { /* 获取字符串 iios/12DDWDFF@122 中的/和@之间的字符串怎么做 */ const char* s = "iios/12DDWDFF@122"; char buf[20]; sscanf( s, "%*[^/]/%[^@]", buf ); printf( "%s\n", buf ); return 0; }
自己通常没用到,但是认为和实用的东西:
1. * 亦可用于格式中, (即 %*d 和 %*s) 加了星号 (*) 表示跳过此数据不读入
2.集合操作 %[a-z] 表示匹配a到z中任意字符,贪婪性(尽可能多的匹配)
%[aB'] 匹配a、B、'中一员,贪婪性
%[^a] 匹配非a的任意字符,并且停止读入,贪婪性