gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:26 24 4
gpt4 key购买 nike

您好,我正在尝试将 char 转换为 int。我有一个通过 scanf 输入的 char 数组,“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

最佳答案

你问:

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

这样做是因为:

&aBuff[0] == aBuff;

它们是等价的。数组中第一个元素的地址与引用数组本身时获得的地址相同。所以你是说:

aDork[0] = atoi(aBuff);

它在 aBuff 处获取整个 string 并计算其整数值。如果你想获得一个digit的值,这样做:

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

现在

aDork[0] == 1;

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

关于使用atoi将char数组转换为int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27260260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com