当前位置: 代码迷 >> 综合 >> sscanf()和sprintf()函数
  详细解决方案

sscanf()和sprintf()函数

热度:33   发布时间:2023-12-02 06:26:54.0

一、sscanf()函数

# include <iostream>
# include <string>using namespace std;int main ()
{//%*d跳过数据string str1="12345abcde";string str2;sscanf(str1,"%*d",str2);cout<<str2<<endl;//输出abcdesscanf(str1,"%*s",str2);cout<<str2<<endl;//输出空,因为第一个字符是数字,不满足%*s所以直接终止执行//%s跳过数据string str1="abcde 12345";//如果不加空格会全部跳过string str2;sscanf(str1,"%*s",str2);cout<<str2<<endl;//输出abcdesscanf(str1,"%*s",str2);cout<<str2<<endl;//输出空,因为第一个字符是数字,不满足%*s所以直接终止执行//读指定宽度字符string str1="12345abcde";string str2;sscanf(str1,"%6d",str2);cout<<str2<<endl;//输出abcdea//匹配区间string str1="abcde12345";string str2;sscanf(str1,"%[a-c]",str2);cout<<str2<<endl;//输出abc//匹配具体几个字符string str1="abcde12345";string str2;sscanf(str1,"%[ac]",str2);cout<<str2<<endl;//输出a,因为b不符合,所以就退出了//匹配区间string str1="abcde12345";string str2;sscanf(str1,"%[^1-5]",str2);//匹配非1到5的字符cout<<str2<<endl;//输出abcde//匹配具体几个字符string str1="abcde12345";string str2;sscanf(str1,"%[^c]",str2);//匹配非c的字符cout<<str2<<endl;//输出abreturn 0;
}

二、sprintf()函数

# include <iostream>
# include <string>using namespace std;int main ()
{//格式化转化字符string str;sprintf(str,"Hello %s","C++");cout<<str<<endl;//输出Hello C++//格式化数字string str;sprintf(str,"Hello %d",123);cout<<str<<endl;//输出Hello 123return 0;
}

  相关解决方案