如何在 C 和 C++ 中將字元轉換為 int?


C 語言中,有三種方法可以將 char 型別的變數轉換為 int。這些方法如下 −

下面是一個在 C 語言中將 char 轉換為 int 的示例,

示例

 實際演示

#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
   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++ 語言中,有以下兩種方法可以將 char 型別的變數轉換為 int −

  • stoi()
  • 型別轉換

下面是一個在 C++ 語言中將 char 轉換為 int 的示例,

示例

 實際演示

#include <iostream>
#include <string>
using namespace std;
int main() {
   char s1[] = "45";
   char c = 's';

   int x = stoi(s1);
   cout << "The value of x : " << x;

   int y = (int)(c);
   cout << "\nThe value of y : " << y;

   return 0;
}

輸出

輸出如下

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

更新於: 15-9 月-2023

23K+ 瀏覽

啟動您的 職業生涯

透過完成課程來獲得認證。

開始
廣告