1. 程式人生 > >sprintf() 和 sscanf()

sprintf() 和 sscanf()

ota 逗號 nth sunday for str 字符串 %d string.h 字符

sprintf()函數:將格式化的數據寫入字符串
格式:
int sprintf(char str, char format ,[argument,......]);
返回值類型 sprintf(要寫入數據的字符串,格式,[變量............])

forex:

#include <stdio.h>
#include <math.h>//為了下文中的M_PI
int main()
{
char str[20];//定義一個字符數組,長度為20
int a = 0;//定義一個int類型的a,用來存儲sprintf()的返回值
a = sprintf(str,"%d",M_PI);

puts(str);//輸出字符串str
printf("%d\n"a);//輸出返回值
return 0;
}

結果為:
3.141593
8

可以看出
【返回值】成功則返回參數str 字符串長度,失敗則返回-1,錯誤原因存於errno 中。

printf(); 和 sprintf(); 比較而言,前者是將格式數據打印在屏幕上,後者是將格式數據打印在字符串中。
printf("%s,%c,%d",x,y,z); //將x,y,z 已 逗號隔開的形式 打印在屏幕上。
sprintf(str,"%s,%c,%d",x,y,z) // 將x,y,z 已逗號隔開的形式 寫入數組。

forex:
#include <stdio.h>
int main()
{
char str[100];
char x[15] = "input data";
char y = ‘T‘;
int z = 100;
printf("%s,%c,%d",x,y,z);
sprintf(str,"%s,%c,%d",x,y,z);
puts(str);
return 0;
}

結果為:
   input data,T,100
     input data,T,100

sscanf();函數 從字符串讀取格式化輸入
格式:
int sscanf(const char str, const char

format, ...)
返回值類型 sscanf(要讀取內容的字符串,格式,.....)

forex:
#include <stdio.h>
#include <string.h>
int main()
{
int year,day,a;
char month[10],weekday[10],total[100];
strcpy(total,"sunday June 15 2018");
a = sscanf(total,"%s %s %d %d",weekday,month,&day,&year);//將total裏面的數據從左之後取出來,並存儲到相應類型的變量中
//變量使用的是地址,weekday和month使用的是字符數組首地址,day和year由於是int類型,所以需要加上取地址符
printf("%d\n",a)//輸出返回值
printf("%s %s %d %d\n",weekday,month,day,year);
return 0;
}

結果是:
4
sunday June 15 2018

sscanf() 與 sprintf() 類比 scanf() 與 printf()

sprintf() 和 sscanf()