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

การแปลง char เป็น int ใน C และ C++

ภาษา C (3 วิธี)

  • sscanf()
  • atoi()
  • Typecasting

ตัวอย่าง C

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

int main() {
    const char *str = "12345";
    char c = 's';
    int x, y, z;
    
    sscanf(str, "%d", &x);      // Using sscanf
    printf("\nThe value of x : %d", x);
    
    y = atoi(str);              // Using atoi()
    printf("\nThe value of y : %d", y);
    
    z = (int)(c);               // Using typecasting (ASCII value)
    printf("\nThe value of z : %d", z);
    return 0;
}

ผลลัพธ์

The value of x : 12345
The value of y : 12345
The value of z : 115

ภาษา C++ (2 วิธี)

  • stoi() (C++11) − แปลง String เป็น int
  • Typecasting − ได้ค่า ASCII

ตัวอย่าง C++

#include <iostream>
#include <string>
using namespace std;

int main() {
    char s1[] = "45";
    char c = 's';
    int x = stoi(s1);           // String to int
    cout << "The value of x : " << x;
    int y = (int)(c);           // Char to ASCII
    cout << "\nThe value of y : " << y;
    return 0;
}

ผลลัพธ์

The value of x : 45
The value of y : 115

สรุป

วัตถุประสงค์CC++
String "123" → int 123sscanf, atoistoi (แนะนำ)
Char 'A' → ASCII 65(int)char(int)char