[英]Casting char array into int array using atoi
Hello I'm attempting to convert a char into an int. 您好,我正在尝试将char转换为int。 I have a char array that was inputted through scanf
, "10101" and I want to set an int array's elements equal to that char arrays elements. 我有一个通过scanf
“ 10101”输入的char数组,并且我想要设置一个与该char数组元素相等的int数组元素。
example input: 输入示例:
10101 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
Now I want aDork[0]
to equal aBuff[0]
which would be 1
. 现在,我希望aDork[0]
等于aBuff[0]
,该aBuff[0]
1
。
Below is what I have so far. 以下是到目前为止的内容。
//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
You ask: 你问:
aDork[0] = atoi(&aBuff[0]); // why doesnt this print 1? Currently prints 10101
It does so because: 这样做是因为:
&aBuff[0] == aBuff;
they're equivalent. 他们是等效的。 The address of the first element in the array is the same address you get when referencing the array itself. 数组中第一个元素的地址与引用数组本身时获得的地址相同。 So you're saying: 所以你说:
aDork[0] = atoi(aBuff);
which takes the whole string at aBuff
and evaluates its integer value. 它将整个字符串放在aBuff
并求出其整数值。 If you want to get the value of a digit , do that: 如果要获取数字值,请执行以下操作:
aDork[0] = aBuff[0] - '0'; // '1' - '0' == 1, '0' - '0' == 0, etc.
and now 现在
aDork[0] == 1;
Working example: https://ideone.com/3Vl3aI 工作示例: https : //ideone.com/3Vl3aI
this code is working as expected, but you are not understanding how atoi works: 该代码可以正常工作,但是您不了解atoi的工作原理:
Now I want aDork[0] to equal aBuff[0] which would be 1 现在我想让aDork [0]等于aBuff [0]等于1
but 但
aDork[0] = atoi(aBuff);
means aDork[0] will store the integer value of aBuff. 表示aDork [0]将存储aBuff的整数值。 Meaning the value 10101 and not the string "10101" 表示值10101,而不是字符串“ 10101”
PS: you didn't need an array of char for aDork: PS:aDork不需要char数组:
int aDork = 0;
aDork = atoi(aBuff);
is enough. 足够。
Assuming aBuff
contains a string of zeros and ones (that does not exceed the length of aDork
), the following would transfer these values to an integer array. 假设aBuff
包含一串零和一(不超过aDork
的长度),则以下内容会将这些值传输到整数数组。
for (int i = 0; i < strlen(aBuff); i++)
{
aDork[i] = (aBuff[i] - '0');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.