Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

แปลง String ↔ Number ในภาษา C (sscanf, sprintf)

ในภาษา C มีฟังก์ชันมาตรฐาน 2 ตัวสำหรับแปลงระหว่าง String และ Number:

  • sscanf() - String → Number (Scan from String)
  • sprintf() - Number → String (Print to String)

1. String → Number: sscanf()

int sscanf(const char *str, const char *format, ...);

ทำงานเหมือน scanf() แต่อาจจาก String แทน stdin

ตัวอย่าง: แยกวันที่

#include <stdio.h>

int main() {
    char date_str[] = "02 01 2010";
    int day, month, year;
    
    sscanf(date_str, "%d %d %d", &day, &month, &year);
    
    printf("Day = %d\n", day);     // 2
    printf("Month = %d\n", month); // 1
    printf("Year = %d\n", year);   // 2010
    
    return 0;
}

ตัวอย่าง: แปลงสตริงตัวเลข

char str[] = "12345";
int num;
sscanf(str, "%d", &num);  // num = 12345

float f;
sscanf("3.14159", "%f", &f);  // f = 3.14159

2. Number → String: sprintf()

int sprintf(char *str, const char *format, ...);

ทำงานเหมือน printf() แต่เขียนลง String แทนหน้าจอ

ตัวอย่าง: สร้างวันที่เป็น String

#include <stdio.h>

int main() {
    char date_str[20];
    int day = 2, month = 1, year = 2010;
    
    sprintf(date_str, "%02d/%02d/%04d", day, month, year);
    printf("Date: %s\n", date_str);  // 02/01/2010
    
    // ตัวอย่างอื่นๆ
    char buf[50];
    sprintf(buf, "Value: %d, Hex: %x, Float: %.2f", 255, 255, 3.14);
    printf("%s\n", buf);
    // Value: 255, Hex: ff, Float: 3.14
    
    return 0;
}

ฟังก์ชันเฉพาะเจาะจง (Alternative)

ฟังก์ชันHeader用途
atoi()<stdlib.h>String → int (Simple)
atol()<stdlib.h>String → long
atof()<stdlib.h>String → double
strtol()<stdlib.h>String → long (มี error checking)
strtod()<stdlib.h>String → double (มี error checking)
itoa()Non-standardint → String (หลีกเลี่ยง)

ตัวอย่างใช้ strtol() (แนะนำสำหรับ Production)

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345abc";
    char *endptr;
    long val = strtol(str, &endptr, 10);
    
    printf("Value: %ld\n", val);        // 12345
    printf("Stopped at: '%s'\n", endptr); // "abc"
    
    if(*endptr != '\0')
        printf("Warning: Non-numeric characters found\n");
    
    return 0;
}

สรุปการเลือกใช้

  • sscanf/sprintf - ใช้จัดรูปแบบซับซ้อน, หลายค่า
  • strtol/strtod - ใช้แปลงตัวเลขเดี่ยว ต้องการ Error Handling
  • atoi/atof - ใช้งานง่าย แต่ไม่มี Error Detection