使用atoi将char数组转换为int数组

时间:2014-12-02 22:28:08

标签: c arrays casting char atoi

您好我试图将char转换为int。我有一个通过scanf输入的字符数组," 10101"我想设置一个int数组的元素等于char数组元素。

示例输入:

  

10101

char aBuff[11] = {'\0'};
int aDork[5] = {0};

scanf("%s", aBuff); //aBuff is not equal to 10101, printing aBuff[0] = 1, aBuff[1] = 0 and so on

现在我希望aDork[0]等于aBuff[0] 1 以下是我到目前为止的情况。

//seems to not be working here
//I want aDork[0] to  = aBuff[0] which would be 1
//But aDork[0] is = 10101 which is the entire string of aBuff   
//aBuff is a char array that equals 10101
//aDork is an int array set with all elements set to 0

int aDork[5] = {0}
printf("aBuff[0] = %c\n", aBuff[0]); //value is 1
aDork[0] = atoi(&aBuff[0]); //why doesnt this print 1? Currently prints 10101
printf("aDork[0] = %d\n", aDork[0]); //this prints 1

printf("aBuff[1] = %c\n", aBuff[1]); //this prints 0
printf("aBuff[2] = %c\n", aBuff[2]); //this prints 1

3 个答案:

答案 0 :(得分:3)

你问:

aDork[0] = atoi(&aBuff[0]); // why doesnt this print 1? Currently prints 10101

这样做是因为:

&aBuff[0] == aBuff;
他们是等同的。数组中第一个元素的地址与引用数组本身时获得的地址相同。所以你说:

aDork[0] = atoi(aBuff);

将整个字符串放在aBuff并计算其整数值。如果您想获得数字的值,请执行以下操作:

aDork[0] = aBuff[0] - '0';   // '1' - '0' == 1, '0' - '0' == 0, etc.

现在

aDork[0] == 1;

工作示例:https://ideone.com/3Vl3aI

答案 1 :(得分:1)

此代码按预期工作,但您不了解atoi的工作原理:

  

现在我希望aDork [0]等于aBuff [0],这将是1

  

aDork[0] = atoi(aBuff);

表示aDork [0]将存储aBuff的整数值。意思是值10101而不是字符串" 10101"

PS:你不需要aDork的char数组:

int aDork = 0;
aDork = atoi(aBuff);

就够了。

答案 2 :(得分:1)

假设aBuff包含一串零和一(不超过aDork的长度),以下内容会将这些值传递给整数数组。

for (int i = 0; i < strlen(aBuff); i++)
{
    aDork[i] = (aBuff[i] - '0');
}