C语言sscanf用法解析与正则表达式支持

最近学习算法和输入输出用到的基本知识,首先是我自己写的一份代码参考和学习了很多资源

后面会给出参考资料,他们写得更加详细,正则表达式的支持确实是一大亮点所在

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;

//字符与其他类型转换函数学习

int main() 
{
    //打印到字符串中
    cout << "打印到字符串中的技巧
";
    char s[100];
    sprintf(s, "%d", 123);//整数转为字符
    cout << s << endl;
    sprintf(s, "%5d %5d", 123,46578);//格式控制,左对齐
    cout << s << endl;
    sprintf(s, "%-5d %-5d", 123, 46578);//格式控制,右对齐
    cout << s << endl;
    sprintf(s, "%8x", 14567);//16进制打印
    cout << s << endl;
    cout << "从字符串中读取与指定格式相符的数据
";
    //字符串转换为数字
    int N;
    char s0[100] = "0123456";
    sscanf(s0, "%d", &N);//前导0会被过滤
    cout << N << endl;
    sscanf(s0, "%2d", &N);//按位取宽,01-->1
    cout << N << endl;
    char s1[200];
    sscanf("123456", "%s", s1);
    cout << s1<< endl;
    sscanf("123456abcd", "%[^b]", s1);//取到指定字符为止
    cout << s1 << endl;
    sscanf("123abEFac", "%[^A-Z]", s1);//取到大写字符为止
    cout << s1 << endl;
    string s3 = s1;
    cout << s3;
    return 0;
}

参考资料:

C++中string、char *、char[]的转换

https://www.cnblogs.com/Pillar/p/4206452.html

sscanf函数用法举例 

http://www.cnblogs.com/zhuangwei/p/5296219.html

原文地址:https://www.cnblogs.com/hxh88/p/9316135.html