#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“,同時系統提示程序已經停止。原因就是要寫入的字符串的長度超過了buf的長度,造成緩沖區溢出。使用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);}運行結果:The ASCII code of a is 97.又如,產生10個100以內的隨機數并輸出。#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); // 格式化的數據寫入字符串 } str[offset-1]='/n'; printf(str); return 0;}運行結果:74,43,95,95,44,90,70,23,66,84例子使用了一個新函數srand(),它能產生隨機數。例子中最復雜的部分是for循環中每次調用函數sprintf()往字符數組寫數據的時候,str+foffset為每次寫入數據的開始地址,最終的結果是所有產生的隨機數據都被以整數的形式存入數組中。
新聞熱點
疑難解答