如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP