(转)C语言sprintf函数详解
时间:2010-09-24 来源:nothing3618
printf可能是许多程序员在开始学习C语言时接触到的 第二个函数(我猜第一个是main),说起来,自然是老朋友了,可是,你对这个老朋友了解多吗?你对它的那个孪生兄弟sprintf了解多吗?在将各种类 型的数据构造成字符串时,sprintf的强大功能很少会让你失望。
//把整数123打印成一个字符串保存在s中。
sprintf(s, “%d”, 123); //产生“123″
sprintf(s, “%8d%8d”, 123, 4567); //产生:“ 123 4567″
sprintf(s, “%-8d%8d”, 123, 4567); //产生:“123 4567″
sprintf(s, “%8x”, 4567); //小写16进制,宽度占8个位置,右对齐
sprintf(s, “%-8X”, 4568); //大写16进制,宽度占8个位置,左对齐
sprintf(s, “%08X”, 4567); //产生:“000011D7″
short si = -1;
sprintf(s, “%04X”, si);
sprintf(s, “%04X”, (unsigned short)si);
unsigned short si = -1;
sprintf(s, “%04X”, si);
sprintf(s, “%f”, 3.1415926); //产生“3.141593″
sprintf(s, “%10.3f”, 3.1415626); //产生:“ 3.142″
sprintf(s, “%-10.3f”, 3.1415626); //产生:“3.142 ”
sprintf(s, “%.3f”, 3.1415626); //不指定总宽度,产生:“3.142″
int i = 100;
sprintf(s, “%.2f”, i);
sprintf(s, “%.2f”, (double)i);
for(int i = 32; i < 127; i++) {
printf(”[ %c ]: %3d 0x%#04X\n”, i, i, i);
}
char* who = “I”;
char* whom = “CSDN”;
sprintf(s, “%s love %s.”, who, whom); //产生:“I love CSDN. ”
char a1[] = {’A', ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’};
char a2[] = {’H', ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’};
sprintf(s, “%s%s”, a1, a2); //Don’t do that!
sprintf(s, “%7s%7s”, a1, a2);
sprintf(s, “%.7s%.7s”, a1, a2);//产生:“ABCDEFGHIJKLMN”
sprintf(s, “%.6s%.5s”, a1, a2);//产生:“ABCDEFHIJKL”
sprintf(s, “%.*s%.*s”, 7, a1, 7, a2);
sprintf(s, “%.*s%.*s”, sizeof(a1), a1, sizeof(a2), a2);
sprintf(s, “%-*d”, 4, ‘A’); //产生“65 ”
sprintf(s, “%#0*X”, 8, 128); //产生“0X000080″,“#”产生0X
sprintf(s, “%*.*f”, 10, 2, 3.1415926); //产生“ 3.14″
sprintf(s, “%u”, &i);
sprintf(s, “%08X”, &i);
sprintf(s, “%p”, &i);
我觉得它实际上就相当于:
sprintf(s, “%0*x”, 2 * sizeof(void *), &i);
int len = sprintf(s, “%d”, i);
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
srand(time(0));
char s[64];
int offset = 0;
for(int i = 0; i < 10; i++) {
offset += sprintf(s + offset, “%d,”, rand() % 100);
}
s[offset - 1] = ‘\n’;//将最后一个逗号换成换行符。
printf(s);
return 0;
}
time_t t = time(0);
//产生“YYYY-MM-DD hh:mm:ss”格式的字符串。
char s[32];
strftime(s, sizeof(s), “%Y-%m-%d %H:%M:%S”, localtime(&t));
①获取System时间: void GetSystemTime(LPSYSTEMTIME lpSystemTime); 下面是例子:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
SYSTEMTIME st; //定义存放时间的结构体
char strTime[256];
int n=0;
GetSystemTime(&st);
n = sprintf(strTime,”Year:\t%d\n”,st.wYear);
n += sprintf(strTime+n,”Month:\t%d\n”,st.wMonth);
n += sprintf(strTime+n,”Day:\t%d\n”,st.wDay);
n += sprintf(strTime+n,”Date:\t%d\n”,st.wDayOfWeek);
n += sprintf(strTime+n,”Hour:\t%d\n”,st.wHour);
n += sprintf(strTime+n,”Minute:\t%d\n”,st.wMinute);
n += sprintf(strTime+n,”Second:\t%d\n”,st.wSecond);
n += sprintf(strTime+n,”MilliSecond:\t%d\n”,st.wMilliseconds);
printf(”%s”,strTime);
system(”pause”);
}