c++_数字格式化

sscanf

读取格式化的字符串中的数据;从一个字符串中读进与指定格式相符的数据

基本用法,取字符串

string strSrc = "1234456";
char strTag[521];
sscanf(strSrc.c_str(),"%s",strTag);
sscanf(strSrc.c_str(),"%4s",strTag);

转换为整型数

string strSrc = "123456";
int x;
sscanf(strSrc.c_str(),"%d",&x);
sscanf(strSrc.c_str(),"%3d",&x);

停止和范围

sscanf(strSrc,"%[^a]",str); //遇到“a”停止
sscanf(strSrc,"%[^c]",str); //遇到“c”停止
sscanf(strSrc,"%[1-9A-Z]",str); //只取范围1-9和A-Z的字符
sscanf(strSrc,"%[^b-z]",str); //遇到“b-z”停止
sscanf(strSrc,"%[^c-z]",str); //遇到“c-z”停止

格式转换

char source[512] = "2015:8:1";
int a,b,c;
sscanf(source,"%d:%d:%d",&a,&b,&c);
// 注意:这个地方a、b、c必须加引用,否则会报错。

sprintf

sprintf与printf的用法很类似,只不过是前者输出到指定的目标,后者输出到屏幕。
sprintf函数的格式:int sprintf( char *string_buffer, const char *format_string[, args] ); 除了前两个参数固定外,可选参数可以是任意个。buffer是字符数组名;format是格式化字符串(像:“%3d%6.2f%#x%o”,%与#合用时,自动在十六进制数前面加上0x)。只要在printf中可以使用的格式化字符串,在sprintf都可以使用。其中的格式化字符串是此函数的精华。

#include<iostream>
#include<cstdio>
using namespace std; 
void test(int x)
{
 char buf[20];
 sprintf(buf,"%d",x);
 cout << buf << endl;

 sprintf(buf,"buf = %d",x);
 cout << buf << endl;

 sprintf(buf,"buf = %08d",x);
 cout << buf << endl;
}
void test0()
{
 test(1);
 test(2);
}
int main(){
    test0();
}

控制精度

char str[20]; 
double f=12.3456*;
sprintf(str,"%6.2f",f) ; // 整数保留6位,小数保留2位

多个数值数据连接起来

char str[20];
int a=6,b=9;
sprintf(str,"%d%d",a,b); // 拼接两个数字
sprintf(str,"%02x%04x",a,b); // 转六进制拼接,保留指定位数,位数不足补0

数据格式化

// 格式转换指定符
// %%    	打印 %
// %c    	打印单个字符
// %s		打印字符串
// %u		打印无符号整数为十进制形式
// %d/%i	打印有符号整数为十进制形式
// %o		打印无符号整数为八进制形式
// %x/%X	打印无符号整数为十六进制形式
// %f/%F	打印浮点数为十进制形式
// %e/%E	打印浮点数为十进制指数形式
// %a/%A	打印浮点数为十六进制形式
// %g/%G	打印浮点数为十进制小数或十进制指数形式

// 特殊说明
// 1. [%10s] ==> [     Hello]
// const char* s = "Hello";
// 	10 指定字符串的长度为10,不足的用空格填充,默认右对齐
// 2. [%-10s] ==> [Hello     ]
// 	10 指定字符串的长度为10
// 	- 左对齐,不足的用空格填充
// 
// float f = 1.5;
// 1. [%05.2f] ==> [01.50]
// 	05 小数点前不足5位的,最前面添加一个0
// 	.2 小数点后保留2位有效数字
// 
// unsigned int i = 10;
// 1. [%#x] ==> [0xa]
// 	#x 以 0x 、小写 形式打印十六进制数
// 
// %f	对应float 则 %lf 对应double
// %d	对应int 则 %ld 对应long
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值