我有一个char数组s[n]={1-3 2 5 6}
,我想在c ++中用Int数组N [n]转换它,使N [1]保持值1,N [2]保持值-3,所以上。
我已经尝试了函数atoi
,但它将数组的所有值传递给单个Int。请帮帮我。
答案 0 :(得分:0)
我使用从字符到整数的类型转换的简单方法, N [i] =(int)s [i] -'0';
这里 N 是整数数组, s 是字符数组。我只需将字符数组类型转换为整数,它会将其视为s的ASCII代码[一世]。所以我减去'0'字符(这表示数字必须是原始值而不是ascii代码)。
您可以尝试以下代码! 另外,我附上了代码输出的截图。
#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
//character array 's' with length of 5
char s[5] = { '1', '3', '2', '5', '6' };
//before converting , prints the character array
cout << "\t\tCharacter Array" <<endl;
for (int i = 0; i < 5; i++)
{
cout << s[i] << "\t";
}
//integer array 'N' with length of 5
int N[5];
cout << "\n\tConverting Character Array to Integer Array" << endl;
//convert the character array into integer type and assigning the value into integer array 'N'
for (int i = 0; i < 5; i++)
{
N[i] = (int)s[i] - '0';
}
cout << "\t\tInteger Array" << endl;
//after converting , prints the integer array
for (int i = 0; i < 5; i++)
{
cout <<N[i]<<"\t";
}
_getch();
return 0;
}