注册 登录
编程论坛 C++教室

在sscanf中使用正则运算,可以使用char型数组得到的数据,但不能使用int型或者string型的到数据

纯蓝之刃 发布于 2020-02-17 15:10, 1312 次点击
程序代码:
#include<iostream>

using namespace std;

int main()
{
    string sum;
    int num;
    char str[50]={0};
    char buf[] ="There are 008 records in all:";
    sscanf(buf,"%*[^0-9]%[^ ]",str);
    //sscanf(buf,"%*[^0-9]%[^ ]",sum);
   
//sscanf(buf,"%*[^0-9]%[^ ]",&num);

    cout<<"1."<<str<<"\n";
    cout<<"2."<<sum<<"\n";
    cout<<"3."<<num<<endl;

    return 0;
}


在sscanf中使用正则运算,可以使用char型数组得到的数据,但不能使用int型或者string型的到数据?
4 回复
#2
rjsp2020-02-18 09:46
sscanf 不支持 正则运算;
sscanf(buf,"%*[^0-9]%[^ ]",str) 是读取 "008" 到 str 中,这个我看懂了;
sscanf(buf,"%*[^0-9]%[^ ]",sum) 这个的话,sscanf可认识 std::string;
sscanf(buf,"%*[^0-9]%[^ ]",&num) 我猜你想要的是 sscanf(buf,"%*[^0-9]%d",&num) 吧
#3
纯蓝之刃2020-02-18 11:23
应该就是这样吧,第二条我也感觉可能是不识别,毕竟sscanf是c的函数。不过第三条我试了好多次都不对,应该就是你说的%d的问题吧。感谢感谢。
#4
叶纤2020-02-18 16:28
程序代码:

//用正则运算检索字符串比较强大,regex库里,反正我看了一大会,只看懂一些皮毛
#include<iostream>
#include<regex>
#include<string>
using namespace std;
int main()
{
    string str{"dghdyh 1180dh ffh"};
    while(true) {
        regex e("([[:d:]]{1,})");
        smatch m;
        bool found = regex_search(str, m, e);
        if(found)
        {
            cout << "m.str(" "): " << m.str(0) << endl;
        }

        else cout << "Not Found" << endl;
        return 0;

    }
}


#5
叶纤2020-02-18 16:50
sscanf虽然有类似正则运算的符号但是和正则运算还是有一些差距的
比如^这个符号在sscanf是遇到某个字符为止    比如[^A-Z]表示遇到大写字母为止
正则运算运算[^a]表示除了a以外的其它字符
*这个符号也和正则运算里有很大不同
sscanf里表示不读取正则运算里表示任意长度的字符串
如果想要用sscanf建议用
sscanf(const char *str, const char *format, ...)
format里用[=%[*] [width] [modifiers] type =]这样的用法
语法用c语法
1