ปัญหา
คุณหมายถึงอะไรโดยการแปลงสตริงเป็นตัวเลขและการแปลงตัวเลขเป็นสตริงในภาษาการเขียนโปรแกรม C
วิธีแก้ปัญหา
มีสองฟังก์ชั่นสำหรับการแปลง พวกมันคือ −
- sscanf() - แปลงสตริงเป็นตัวเลข
- sprintf () - ใช้สำหรับแปลงตัวเลขเป็นสตริง
การแปลงสตริงเป็นตัวเลข
เราสามารถแปลงสตริงเป็นตัวเลขโดยใช้ฟังก์ชัน sscanf() -
ไวยากรณ์
sscanf (string name, “control string”,variable list)

ตัวอย่าง
#include<stdio.h>
main (){
char a[20] = “02 01 2010”;
int day, mon, yr;
clrscr();
sscanf (a, “%d%d %d”, &day, &mon, &yr);
printf ( “Day =%d”, day);
printf ( “Month = %d”, mon);
printf ( “Year = %d”, yr);
getch ();
} ผลลัพธ์
Day = 02 Month = 01 Year = 2010
การแปลงตัวเลขเป็นสตริง
เราสามารถแปลงสตริงเป็นตัวเลขโดยใช้ sprintf() ฟังก์ชัน −
ไวยากรณ์
sprintf ( string name, “control string”, variable list)

ตัวอย่าง
#include<stdio.h>
main (){
char a[50];
int day,mon,yr;
day = 02;
mon = 01;
yr = 2010;
crlscr();
sprintf (a, “%d/%d/%d”, day, mon, yr);
printf ( “today’s date =%s”,a);
getch ();
} ผลลัพธ์
Today’s date is 02/01/2010.