c++ - 在 C++ 中提取 char 数组的 int

标签 c++

我正在尝试从 char 数组中提取单个字符并将其转换为整数。 我需要从代码中提取数字,例如如果用户输入 A23B,我需要提取 23 并将其存储在单个变量中这是我的代码

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
char code[5] ={'\0'};
cout << "Enter Your Four Digit Code\nExample A23B\n";
cin.getline(code,5);
cout << "You typed:\n" << code;
int a = atoi(code[1]);
int b = atoi(code[2]);
cout << endl <<a <<"\t"<<b;
//Other processing related to number a and b goes here
}

但它不工作并产生以下错误

C:\helo\clan\Test\main.cpp||In function 'int main()':|
C:\helo\clan\Test\main.cpp|12|error: invalid conversion from 'char' to 'const char*'|
C:\helo\clan\Test\main.cpp|12|error:   initializing argument 1 of 'int atoi(const char*)'|
C:\helo\clan\Test\main.cpp|13|error: invalid conversion from 'char' to 'const char*'|
C:\helo\clan\Test\main.cpp|13|error:   initializing argument 1 of 'int atoi(const char*)'|
||=== Build finished: 4 errors, 0 warnings ===|

最佳答案

atoi采用 const char*,而不是 char

如果您需要从“A23B”获取“2”和“3”:

int b = atoi(code + 2);
code[2] = 0;
int a = atoi(code + 1);

如果您需要从“A23B”获取“23”,则:

int a = atoi(code + 1);

关于c++ - 在 C++ 中提取 char 数组的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8835096/

相关文章:

c++ - 返回存储在类中的 C 字符串

c++ - 具有详尽训练数据的神经网络 : Minimal, 开源示例?

c++ - Qt 5 的多个 OpenGL 视口(viewport)

c++ - 如何使用mongodb的c++驱动程序构建程序?

c++ - 从 float array 到 mat ,连接图像 block

c++ - 从 C++ 中的函数输出多个值

c++ - Regedit 看不到从我的代码中插入的注册表值

c++ - C++ 中的组合练习看到速度与 VBA 相比有所下降

c++ - 将字符串从 UTF-8 转换为 ISO-8859-1

c++ - 如何从数组中删除 2 个连续的重复项? C++