C++程序 – char到int的转换

来源:这里教程网 时间:2026-02-16 16:08:00 作者:

C++程序 – char到int的转换

在这里,我们将看到如何使用c++程序将char转换为int。c++中有6种将char型转换为int型的方法:

    使用强制类型转换.使用static_cast.Using sscanf().Using stoi().Using atoi().使用stringstream.

让我们详细讨论每一种方法。

1. 使用强制类型转换

方法1:

    声明并初始化要转换的字符。使用int类型对字符进行类型转换,将字符转换为int类型。使用cout打印整数。

下面是使用类型转换将char类型转换为int类型的c++程序:

// C++ program to convert// char to int using typecasting#include <iostream>using namespace std;  // Driver codeint main() {    char ch = 'A';     cout << int(ch);    return 0;}

输出

65

方法2:

    声明并初始化要转换的字符。声明另一个变量为int N,并将字符ch赋值给N。使用cout打印整数。

下面是使用类型转换将char类型转换为int类型的c++程序:

// C++ program to convert // char to int using typecasting #include <iostream>using namespace std;  // Driver codeint main() {    char ch = 'a';     int N = int(ch);    cout << N;    return 0;}

输出

97

2. 使用 static_cast

可以使用static_cast函数将字符转换为整数。下面是使用static_cast将char转换为int的c++程序:

// C++ program to convert char// to int using static_cast#include <iostream>using namespace std;  // Driver codeint main() {    char ch = 'A';     int N = static_cast<int>(ch);     cout << N;    return 0;}

输出

65

3. 使用sscanf

从s中读取数据,并将其存储在由形参格式中的附加参数指定的位置。下面是使用sscanf()将char转换为int的c++程序:

// C++ program to convert char// to int using sscanf()#include <iostream>using namespace std;  // Driver codeint main() {  const char *s = "1234";   int x;  sscanf(s, "%d", &x);   cout << "\nThe integer value of x : " << x;  return 0;}

输出

The integer value of x : 1234

4. 使用 stoi

c++中的stoi()函数将字符串转换为整数值。下面是使用stoi()将char转换为int的c++程序:

// C++ program to convert char// to int using stoi()#include <iostream>#include <string>using namespace std;  // Driver codeint main() {  char s1[] = "45";  int x = stoi(s1);  cout << "The integer value of x : " << x;  return 0;}

输出

The integer value of x : 45

5. 使用 atoi

如果执行成功,atoi()方法将返回转换后的整数值。如果给定的字符串不能转换为整数,它将返回0。下面是使用atoi()将char转换为int的c++程序:

// C++ program to convert char// to int using atoi()#include <iostream>using namespace std;  // Driver codeint main() {  const char *str = "1234";    int y = atoi(str);   cout << "\nThe integer value of y :" << y;  return 0;}

输出

The integer value of y :1234

6. 使用stringstream

stringstream将一个字符串对象连接到一个流,允许你像读取一个流一样读取它(比如cin)。Stringstream需要包含sstream头文件。stringstream类在处理输入时很有用。
下面是使用string流将char转换为int的c++程序:

// C++ program to convert char// to int using string stream#include <iostream>#include <string>#include <sstream>using namespace std;  // Driver codeint main() {    stringstream string;     string << "5";     int n;     string >> n;    cout << "Integer value is: " << n;    return 0;}

输出

Integer value is: 5

相关推荐