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] 并使用 first 进行转换,这很奇怪,无论输入如何,我都得到了 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]
is a char *
not a char
you无法将 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屋!