C语言 如何正确地将程序参数 *char 转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4324386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast program argument *char as int correctly?
提问by Rebecca Nelson
I'm on a Mac OS X 10.6.5 using XCode 3.2.1 64-bit to build a C command line tool with a build configuration of 10.6 | Debug | x86_64. I want to pass a positive even integer as an argument, so I'm casting index 1 of argv as an int. This seems to work, except it seems that my program is getting the ascii value instead of reading the whole char array and converting to an int value. When I enter 'progname 10', it tells me that I've entered 49, which is what I also get when I enter 'progname 1'. How can I get C to read the entire char array as an int value? Google only showed me (int)*charPointer, but clearly that doesn't work.
我在 Mac OS X 10.6.5 上使用 XCode 3.2.1 64 位构建 C 命令行工具,构建配置为 10.6 | 调试 | x86_64。我想传递一个正偶数作为参数,所以我将 argv 的索引 1 转换为 int。这似乎有效,只是我的程序似乎正在获取 ascii 值,而不是读取整个 char 数组并转换为 int 值。当我输入“progname 10”时,它告诉我我已经输入了 49,这也是我输入“progname 1”时得到的。如何让 C 将整个 char 数组作为 int 值读取?Google 只向我展示了 (int)*charPointer,但显然这不起作用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char **argv) {
char *programName = getProgramName(argv[0]); // gets the name of itself as the executable
if (argc < 2) {
showUsage(programName);
return 0;
}
int theNumber = (int)*argv[1];
printf("Entered [%d]", theNumber); // entering 10 or 1 outputs [49], entering 9 outputs [57]
if (theNumber % 2 != 0 || theNumber < 1) {
showUsage(programName);
return 0;
}
...
}
回答by stacker
回答by unwind
回答by Milan
Lets say you have a 9 as argument. You said you are getting 57, the ascii value.
假设您有一个 9 作为参数。你说你得到 57,ascii 值。
Use the fact that int num = *arg[1] - '0'will give you back the number you need.
使用int num = *arg[1] - '0'可以为您提供所需号码的事实。
if it's a larger number like, 572 then you need
如果它是一个更大的数字,比如 572 那么你需要
char *p = argv[1];
int nr = 0;
int i;
for(i =0; i< strlen(p); i++) {
nr = 10 * nr + p[i] - '0';
}
Add some error checking and its good to go.
添加一些错误检查和它的好去。
Or, depending on what you have, you can use some functions like atoi(), sscanf() etc.
或者,根据您拥有的内容,您可以使用一些函数,如 atoi()、sscanf() 等。
回答by ?imon Tóth
Use atoi()or strol()functions.
用途atoi()或strol()功能。

