char是没有转换为int [英] Char isn't converting to int
问题描述
出于某种原因,我的C程序拒绝的argv元素转换成整数,我想不通为什么。
For some reason my C program is refusing to convert elements of argv into ints, and I can't figure out why.
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);
}
和运行./test 50时,这是输出:
And this is the output when running ./test 50:
50
-1076276207
-1076276207
我曾尝试删除(INT),抛既是*和&安培;之间(INT)和argv [1] - 前者给了我一个5而不是50,但后者给了我类似上面的那个的输出。拆除 - 0的操作没有太大的帮助。我也试过做一个char第一=的argv [1],并首次使用了转换,而是和这个古怪足够给了我一个17无论输入的。
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. Removing the - '0' operation doesn't help much. 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.
我非常困惑。这是怎么回事?
I'm extremely confused. What is going on?
推荐答案
的argv [1]
是的char *
不是字符
您不能在的char *
转换为 INT
。如果你想argv中[1]的第一个字符更改为int你可以做。
argv[1]
is a char *
not a char
you can't convert a char *
to an int
. If you want to change the first character in argv[1] to an int you can do.
int i = (int)(argv[1][0] - '0');
我刚写了这个
#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;
}
和运行它像这样
./testargv 1243
和获得
1243
1
这篇关于char是没有转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!