溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

sprintf() 和 sscanf()

發(fā)布時間:2020-08-19 22:17:33 來源:網(wǎng)絡(luò) 閱讀:524 作者:zhouzwars 欄目:編程語言

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

forex:

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

結(jié)果為:
3.141593
8

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

printf(); 和 sprintf(); 比較而言,前者是將格式數(shù)據(jù)打印在屏幕上,后者是將格式數(shù)據(jù)打印在字符串中。
printf("%s,%c,%d",x,y,z); //將x,y,z 已 逗號隔開的形式 打印在屏幕上。
sprintf(str,"%s,%c,%d",x,y,z) // 將x,y,z 已逗號隔開的形式 寫入數(shù)組。
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;
}

結(jié)果為:
   input data,T,100
     input data,T,100

sscanf();函數(shù) 從字符串讀取格式化輸入
格式:
int sscanf(const char str, const char format, ...)
返回值類型 sscanf(要讀取內(nèi)容的字符串,格式,.....)

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里面的數(shù)據(jù)從左之后取出來,并存儲到相應(yīng)類型的變量中
//變量使用的是地址,weekday和month使用的是字符數(shù)組首地址,day和year由于是int類型,所以需要加上取地址符
printf("%d\n",a)//輸出返回值
printf("%s %s %d %d\n",weekday,month,day,year);
return 0;
}

結(jié)果是:
4
sunday June 15 2018

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI