我正在尝试从 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/