[英]Char isn't converting to int
For some reason my C program is refusing to convert elements of argv into ints, and I can't figure out why. 出于某种原因,我的C程序拒绝将argv的元素转换为int,我无法弄清楚原因。
int main(int argc, char *argv[])
{
fprintf(stdout, "%s\n", argv[1]);
//Make conversions to int
int bufferquesize = (int)argv[1] - '0';
fprintf(stdout, "%d\n", bufferquesize);
}
And this is the output when running ./test 50: 这是运行./test 50时的输出:
50 50
-1076276207 -1076276207
I have tried removing the (int), throwing both a * and an & between (int) and argv[1] - the former gave me a 5 but not 50, but the latter gave me an output similar to the one above. 我试过删除(int),抛出一个*和一个&之间(int)和argv [1] - 前者给了我一个5而不是50,但后者给了我一个类似于上面的输出。 Removing the - '0' operation doesn't help much. 删除 - '0'操作没有多大帮助。 I also tried making a char first = argv[1] and using first for the conversion instead, and this weirdly enough gave me a 17 regardless of input. 我也尝试先制作一个char = argv [1]然后首先使用转换来进行转换,这很奇怪,不管输入如何都给了我一个17。
I'm extremely confused. 我非常困惑。 What is going on? 到底是怎么回事?
尝试使用atoi(argv[1])
(“ascii to int”)。
argv[1]
is a char *
not a char
you can't convert a char *
to an int
. argv[1]
是一个char *
而不是char
你不能将char *
转换为int
。 If you want to change the first character in argv[1] to an int you can do. 如果要将argv [1]中的第一个字符更改为int,则可以执行此操作。
int i = (int)(argv[1][0] - '0');
I just wrote this 我刚写了这个
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv) {
printf("%s\n", argv[1]);
int i = (int)(argv[1][0] - '0');
printf("%d\n", i);
return 0;
}
and ran it like this 像这样跑吧
./testargv 1243
and got 得到了
1243
1
You are just trying to convert a char*
to int, which of course doesn't make much sense. 您只是尝试将char*
转换为int,这当然没有多大意义。 You probably need to do it like: 您可能需要这样做:
int bufferquesize = 0;
for (int i = 0; argv[1][i] != '\0'; ++i) {
bufferquesize *= 10; bufferquesize += argv[1][i] - '0';
}
This assumes, however, that your char*
ends with '\\0', which it should, but probably doesn't have to do. 但是,假设你的char*
以'\\ 0'结尾,它应该是,但可能不必这样做。
(type) exists to cast types - to change the way a program looks a piece of memory. (类型)存在以转换类型 - 改变程序看起来像一块内存的方式。 Specifically, it reads the byte encoding of the character '5' and transfers it to memory. 具体来说,它读取字符'5'的字节编码并将其传输到内存。 A char* is an array of chars, and chars are one byte unsigned integers. char *是字符数组,字符是一个字节无符号整数。 argv[1]
points to the first character. argv[1]
指向第一个角色。 Check here for a quick explanation of pointers in C. So your "string" is represented in memory as: 在这里查看C中指针的快速解释。所以你的“字符串”在内存中表示为:
['5']['0']
when you cast 当你施放
int i = (int) *argv[1]
you're only casting the first element to an int, thus why you 你只是将第一个元素转换为int,这就是为什么你
The function you're looking for is either atoi() as mentioned by Scott Hunter, or strtol() , which I prefer because of its error detecting behaviour. 您正在寻找的函数是Scott Hunter提到的atoi() ,或strtol() ,我更喜欢它因为它的错误检测行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.