ในส่วนนี้เราจะดูวิธีแปลงตัวเลข (integer หรือ float หรือ numeric type อื่น) เป็น string
ตรรกะง่าย ใช้ sprintf() function พิมพ์ค่าหรือบรรทัดเข้า string ไม่ใช่ console ความต่างกับ printf() คืออาร์กิวเมนต์แรกคือ string buffer ที่ต้องการเก็บข้อมูล
Input: User will put some numeric value say 42.26 Output: This program will return the string equivalent result of that number like "42.26"
Algorithm
Step 1: Take a number from the user Step 2: Create an empty string buffer to store result Step 3: Use sprintf() to convert number to string Step 4: End
ตัวอย่างโค้ด
#include<stdio.h> main() { char str[20]; //create an empty string to store number float number; printf("Enter a number: "); scanf("%f", &number); sprintf(str, "%f", number); //make the number into string using sprintf function printf("\nYou have entered: %s", str); }Output:
Enter a number: 46.3258 You have entered: 46.325802