数字转化为字符串,sprintf使用(弱菜笔记)
来源:互联网 发布:mac快速认证信息 编辑:程序博客网 时间:2024/06/06 02:30
注明:以下例程均在code::bolcks(编译器GNU GCC)下运行通过,如果读者不能正确运行,请尝试调整编译器为GNU或GCC。
我们通过几个例子认识sprintf的用法,由此也初窥数字转化为字符串中数据的门径。
最简单直接的方法:一个数字加上0的ASC2码就得到对应字符的ASC2码。
//Example #1#include <stdio.h>int main(){ int a[3]={0, 1, 2}; char s[4]; for(int i = 0; i<3; i++) s[i] = a[i] + '0'; s[3] = '\0'; puts(s);}
输出:012
更简洁的方法是使用sprintf,“sprintf”可以理解为“打印到字符串的函数”。
//Example #2#include <stdio.h>int main(){ char s[10]; int x, y; while(scanf("%d%d", &x, &y) != EOF) { sprintf(s, "%d%d", x, y);//将x,y储存的数据转化为字符串s中的数据 puts(s); } return 0;}输入:1 2
输出:12
在上例中,语句
sprintf(s, "%d%d", x, y);
我理解为是将“%d%d”转化为字符串s的内容,而“%d%d”就是“12”。
以下还有一个例子,摘自C++ reference
//Example #3#include <stdio.h>int main (){ char buffer[50]; int n, a=5, b=3; //建立字符串buffer,n是buffer的长度,包括空格但不包括‘\0’ n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a %d char long string\n",buffer,n); return 0;}输出:[5 plus 3 is 8] is a 13 char long string
- 数字转化为字符串,sprintf使用(弱菜笔记)
- 将数字转化为字符串——sprintf (可用于linux下)
- 字符串转化为数字(不使用库函数)
- 字符串转化为数字
- 字符串转化为数字
- 字符串转化为数字
- 【学习笔记】关于数字转化为字符串,字符串转化为数组。
- Unicode-数字转化为字符串
- 字符串转化为数字函数
- 数字转化为字符串函数
- 字符串转化为数字函数
- 数字转化为字符串函数
- js字符串转化为数字
- 将字符串转化为数字
- 字符串转化为数字 aotf
- 将数字转化为字符串
- Nodejs -- 字符串转化为数字
- 函数:字符串转化为数字
- HDU 1541 star 树状数组
- oracle 游标详解
- EditText之边框颜色
- PHP学习笔记-函数
- IOS学习之十六:网络数据的XML解析
- 数字转化为字符串,sprintf使用(弱菜笔记)
- MySql数据库连接时DriverManager.getConnection(url,user,pass)出错
- 各种Adapter的用法
- 我的CSDN博客下载器,下载博客文章保存为mht文件
- 杭电ACM 2037 今年暑假不AC
- ubuntu下解决sublime text无法输入中文问题
- 【STL】警惕istringstream数据格式化误区
- HDU 4335 What is N? 多校4(数论)
- 读书笔记整理七:位图索引