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

วิธีแปลง Char เดียวเป็น Int ใน C++

ภาพรวม

ใน C++ Character (char) เก็บเป็นรหัส ASCII/Unicode (Integer) การแปลง Char ตัวเลข ('0'-'9') เป็นค่า Int จริง ทำได้โดยการลบค่า ASCII ของ '0' (ซึ่งเท่ากับ 48)

วิธีการแปลง

วิธีที่ 1: ลบ '0' (แนะนำ - Readable, Portable)


char c = '8';
int value = c - '0';  // '8' (56) - '0' (48) = 8
cout << value;  // 8

วิธีที่ 2: ลบ 48 โดยตรง (Magic Number - ไม่แนะนำ)


char c = '8';
int value = c - 48;  // 56 - 48 = 8
cout << value;  // 8

ตัวอย่างโค้ดครบถ้วน

#include <iostream>
using namespace std;

int main() {
    char c = '8';
    
    // วิธีที่ 1: ลบ '0' (แนะนำ)
    int method1 = c - '0';
    cout << "Method 1 (c - '0'): " << method1 << "\n";
    
    // วิธีที่ 2: ลบ 48
    int method2 = c - 48;
    cout << "Method 2 (c - 48): " << method2 << "\n";
    
    // ตัวอย่างหลายตัวอักษร
    string digits = "12345";
    cout << "\nConvert string digits:\n";
    for (char ch : digits) {
        if (ch >= '0' && ch <= '9') {
            int val = ch - '0';
            cout << ch << " -> " << val << "\n";
        }
    }
    
    return 0;
}

ผลลัพธ์


Method 1 (c - '0'): 8
Method 2 (c - 48): 8

Convert string digits:
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5

ขยาย: แปลง String เลขเป็น Integer

1. Manual Conversion (Loop)


int stringToInt(const string& str) {
    int result = 0;
    for (char ch : str) {
        if (ch < '0' || ch > '9') throw invalid_argument("Not a digit");
        result = result * 10 + (ch - '0');
    }
    return result;
}

2. Standard Library Functions


#include <string>

// C++11: std::stoi, std::stol, std::stoll
string s = "12345";
int val = stoi(s);        // 12345
long val2 = stol(s);      // 12345
long long val3 = stoll(s); // 12345

// C Style: atoi, strtol
int val4 = atoi(s.c_str());  // No Error Checking
// strtol ดีกว่า: มี Error Checking, Base Support

3. String Streams (C++98)


#include <sstream>
#include <string>

int stringToIntSS(const string& str) {
    stringstream ss(str);
    int val;
    ss >> val;
    if (ss.fail() || !ss.eof()) throw invalid_argument("Invalid integer");
    return val;
}

การแปลง Char อื่นๆ

การแปลงโค้ดตัวอย่าง
Digit Char → Intc - '0''5' → 5
Uppercase Char → Index (0-25)c - 'A''C' → 2
Lowercase Char → Index (0-25)c - 'a''c' → 2
Char → ASCII Codestatic_cast<int>(c)'A' → 65
Int (0-25) → Uppercase Charchar('A' + i)2 → 'C'
Int (0-25) → Lowercase Charchar('a' + i)2 → 'c'

ข้อควรระวัง

  • ตรวจสอบ isdigit(c) หรือ c >= '0' && c <= '9' ก่อนแปลง
  • char อาจเป็น Signed หรือ Unsigned ขึ้นอยู่กับ Implementation
  • สำหรับ Unicode/UTF-8: ต้องใช้ Library เฉพาะ (ICU, std::wstring_convert deprecated)
  • C++17: std::from_chars เร็วกว่า stoi ไม่ Throw Exception, No Locale

C++17 std::from_chars (High Performance)


#include <charconv>
#include <string>

bool fastStringToInt(const string& str, int& out) {
    auto result = std::from_chars(str.data(), str.data() + str.size(), out);
    return result.ec == std::errc() && result.ptr == str.data() + str.size();
}