#include <stdio.h>main(){ char buf[10]; sprintf(buf, "The length of the string is more than 10"); printf("%s", buf);}編譯并運行,屏幕上輸出”The length of the string is more than 10“,同時系統(tǒng)提示程序已經(jīng)停止。原因就是要寫入的字符串的長度超過了buf的長度,造成緩沖區(qū)溢出。使用snprintf()來代替sprintf()將能夠很好的解決這個問題。【實例】打印字母a的ASCII值。#include <stdio.h>main(){ char a = 'a'; char buf[80]; sprintf(buf, "The ASCII code of a is %d.", a); printf("%s", buf);}運行結(jié)果:The ASCII code of a is 97.又如,產(chǎn)生10個100以內(nèi)的隨機數(shù)并輸出。#include<stdio.h>#include<stdlib.h>#include<time.h>int main(void){ char str[100]; int offset =0; int i=0; srand(time(0)); // *隨機種子 for(i = 0;i<10;i++) { offset+=sprintf(str+offset,"%d,",rand()%100); // 格式化的數(shù)據(jù)寫入字符串 } str[offset-1]='/n'; printf(str); return 0;}運行結(jié)果:74,43,95,95,44,90,70,23,66,84例子使用了一個新函數(shù)srand(),它能產(chǎn)生隨機數(shù)。例子中最復雜的部分是for循環(huán)中每次調(diào)用函數(shù)sprintf()往字符數(shù)組寫數(shù)據(jù)的時候,str+foffset為每次寫入數(shù)據(jù)的開始地址,最終的結(jié)果是所有產(chǎn)生的隨機數(shù)據(jù)都被以整數(shù)的形式存入數(shù)組中。
新聞熱點
疑難解答