0
点赞
收藏
分享

微信扫一扫

字符串总结2

尤克乔乔 2022-12-08 阅读 40



char* 和 int, float 等的格式化转换

从字符串中提取指定类型数字或子串,这种情形也是非常的常见。大部分的情形都可以用sscanf()​和 sprintf() 这两个函数来实现,如果要求复杂,那么就用正则库或自己手写。一个例子如下:

#include <iostream>

#include <string>

#include<stdio.h>

 

int main() {

    // 从字符串中提取数字

    char* p = "192.168.1.1";

    int a[4];

    sscanf(p, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]);

    std::cout << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3] << "\n";

 

    // 从字符串中提取数字,指定的字符串

    char* p2 = "170 60 Alice";

    int height, weight;

    char name[20];

    sscanf(p2, "%d %d %s", &height, &weight, name);

    std::cout << name << " height: " << height << " weight: " << weight << "\n";

 

    // 浮点型数字转字符串,并四舍五入保留指定位数小数

    double pi = 3.1415;

    char str[50];

    sprintf(str, "%s %.3f", "pi is:", pi);

    std::cout << str << "\n";  // 输出 3.142

 

    return 0;

}



举报

相关推荐

0 条评论