snprintf函数的常见功能

以前将各种整型数浮点数转换为字符串时都要借助stringstream类,不仅麻烦,而且对stringstream的了解不够,经常出现一些奇怪的错误,现在有了snprintf,类似的转换功能实现起来相当容易。下面转入正题。

使用snprintf函数前,要记住包含头文件

下面的函数声明摘自博客snprintf函数用法,但原文没有提到如何实现基本数据类型与字符串的转换。

int snprintf(char *restrict buf,  size_t n,  const char * restrict  format, ...);

函数说明:最多从源串中拷贝n1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n 的话,将不会溢出。

函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。


(以下程序均在Dev-C++上通过)

1、整型数字转换为字符串。

#include
#include
#include
using namespace std;

int main() {
    char a[10];
    int j = 12;
    snprintf(a, sizeof(a), "%d", j); //a表示目标字符串,sizeof(a)是转换的字符数,“%d”待转类型,j待转整型常量。
    cout << a << endl;
} 

输出结果为:12


2、浮点型转换为字符串。

#include
#include
#include
using namespace std;

int main() {
    char a[10];
    double i = 12.532423;
    snprintf(a, sizeof(a), "%lf", i);    
    cout << a << endl;
    snprintf(a, sizeof(a), "%0.2lf", i); //设置转换的精度
    cout << a << endl;
}
输出结果为:

12.532423
12.53


3、拷贝字符串。

#include
#include
#include
using namespace std;

int main() {
    char a[10];
    char c[] = "dskcdsvkjgch";
    snprintf(a, sizeof(a), "%s", c);    //以a的数组长度作为转换的位数,则最多拷贝9为,最后加\0。
    cout << a << endl;              
    snprintf(a, sizeof(c), "%s", c);    //以c的字符长度作为转换的位数,系统会自动将a的数组长度调整到刚好能匹配c的字符。
    cout << a << endl;	
}
输出结果:

dskcdsvkj
dskcdsvkjgch


使用snprintf的另一个好处是可以实现字符串的连接,再加上其相对安全的功能,strcat基本就可以抛弃了

#include
#include
#include
using namespace std;

int main() {
    char a[10];
    char c[] = "dskc";
    snprintf(a, sizeof(a), "%s", c);  //以数组名作为参数,实际上是从数组 第一位开始拷贝字符。
	cout << a << endl;
	snprintf(a+4, sizeof(a), "%s", c);  //实现连接,要注意连接开始的位置,之前a的前四位有字符,因此从第五位开始,对应数组脚标4,小于4,则之前的字符被覆盖,大于4,则a[4]为'\0';
	cout << a << endl;	
}
输出结果:

dskc
dskcdskc


你可能感兴趣的:(snprintf函数的常见功能)