使用 arg[v] 作为 int? - Objective C

Using arg[v] as int? - Objective C

我试图在 xcode 中使用 Objective C 的程序开始时将参数传递给整型变量。到目前为止,我发现的大多数方法只是给我各种错误消息或使我的 VM 崩溃。

int numcols, numrows;

int main(int argc, const char * argv[]) {
@autoreleasepool {

    if (argc != 3){
        NSLog(@"%2s", "Wrong number of arguments");
        exit(1);
    }

    //numrows = (int)(argv[1] - '0'); 
    //numcols = (int)(argv[2] - '0'); These lines cause a crash
    numrows = 3;
    numcols = 4;

我希望 numrows 接受第一个参数,而 numcols 接受第二个参数。我进入 xcode 中的设置,将起始参数更改为 3 和 4,但如果我检查或打印它们,它们会以随机数形式出现。

首先你的问题不是很清楚,我能说多少明白。 argc 表示参数计数,argv 表示参数值。如果你想将 char 转换为 int。试试这个

[[NSString stringWithFormat:@"%s", argv[2]] intValue];

argvC 字符串 的数组。您不能只将字符串转换为整数,您需要 解析 字符串以生成它表示的整数值。

您可以自己编写代码来执行此操作,但幸运的是有库函数可以处理此问题,例如,请参阅 strtol 它将解析字符串并生成 long.

HTH