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

แปลง ASCII Values เป็น String ใน C++

ภาพรวมปัญหา

ได้รับสตริงที่เป็นรหัส ASCII ต่อกัน ต้องแปลงกลับเป็นข้อความ

ตัวอย่าง

Input: "104101108108111443211911111410810033"
Output: "hello, world!"

วิธีแก้ปัญหา

  1. อ่านตัวเลขทีละหลักสร้างค่า
  2. ถ้าค่าอยู่ในช่วง 32-122 (Printable ASCII) → แปลงเป็น Char พิมพ์ แล้ว Reset ค่า

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

void convert_ASCII(string str, int len) {
    int num = 0;
    for (int i = 0; i < len; i++) {
        num = num * 10 + (str[i] - '0');
        if (num >= 32 && num <= 122) {
            char ch = (char)num;
            cout << ch;
            num = 0;
        }
    }
}

int main() {
    string str = "104101108108111443211911111410810033";
    int len = str.length();
    convert_ASCII(str, len);
    return 0;
}

ผลลัพธ์ (Output)

hello, world!