您的位置:首页 > 其它

strdup();strtok();sscanf(…

2017-06-29 10:16 477 查看
//例(strdup();strtok();sscanf()的使用)

void main( )

{

   char *pts =
"(1,2);(2,4);(5,9)";

   char *data =
strdup(pts);

   char *p = strtok(data,
";");

   while (p)

   {

       
// 每个Point 使"x,y" 格式

      
 int x, y;

      
 if (sscanf(p, "%d,%d", &x, &y) ==
2)

      
 {

      
    CvPoint pt =
{ x, y };

           points.push_back(pt);

      
 }

     
 p = strtok(0, ";");

  }

  free(data);

}

 

函数介绍:

char *strdup(char
*s):

功 能: 将字符串拷贝到新建的内存位置处

strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。

返回一个指针,指向为复制字符串分配的空间;如果分配空间失败,则返回NULL值。

①.// strdup.c

#include

#include

#include

int main()

{

char *s="Golden Global View";

char *d;

clrscr();

d=strdup(s);

printf("%s",d);

free(d);

getchar();

return 0;

}

运行结果:

Golden Global View

 

 

char *strtok(char s[], const char *delim);

分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

例如:strtok("abc,def,ghi",","),最后可以分割成为abc def
ghi.尤其在点分十进制的IP中提取应用较多。

 

strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0
字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。

#include

#include

int main(void)

{

    char
input[16] = "abc,d";

    char
*p;

    p =
strtok(input, ",");

    if (p)
printf("%s\n", p);

    p =
strtok(NULL, ",");

    if (p)
printf("%s\n", p);

    return
0;

}

 

int sscanf( const
char *buffer,const char *format,[argument ]...);

buffer存储的数据

format格式控制字符串

argument 选择性设定字符串

sscanf会从buffer里读进数据,依照format的格式将数据写入到argument里。

 

成功则返回参数数目,失败则返回-1,错误原因存于errno中。

 

sscanf与scanf类似,都是用于输入的,只是后者以键盘(stdin)为输入源,前者以固定字符串为输入源。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: