摘要:我最近一直在玩Unix终端,并决定构建一个小型的Objective-C应用程序,以测试将参数传递给"main"的实际执行方式。我在构建应用程序时牢记 std=c99。
测试:如果我将值硬编码为 argv 和 argc,一切正常:main的前几行中的 argv[0] 和 argv[1]。
问题:如果我注释 argv[0] 和 argv[1] 并从 unix 终端运行我的应用程序,该应用程序将永远无法运行,这就是为什么我想知道终端是否会附加任何我不知道的有趣字符——
下面是一段代码:1.请注意,字典只是一个结构体2. 想法?
int main(int argc, char * argv[])
{
//argv[0] = "prog";
//argv[1] = "four";
NSLog(@"request from: %s, entered string: %s, # of arguments: %i", argv[0], argv[1], argc);
//argc = 2;
if (argc >= 2)
{
if (translate(argv, argc));
else
NSLog(@"%s", "Unable to find request in dictionary");
}
else
NSLog(@"insufficient arguments");
return 0;
}
BOOL translate(char * search[], int size)
{
const int buffer = 6;
Dictionary dic[] =
{{"one", "1"},
{"two", "2"},
{"three", "3"},
{"four ", "4"},
{"five", "5"},
{"six", "6"}
};
char * temp = search[size - 1];
NSLog(@"temp value: %s", temp);
int i = 0;
for (; i < buffer; ++i)
{
char * temp2 = dic[i].num;
NSLog(@"steped into for loop - with currect struct value: %s", temp2);
if (temp == temp2)
{
NSLog(@"steped into if stamtement");
NSLog(@"%s", dic[i].translate);
return YES;
}
}
return NO;
}
所以最后一次...
你不能用==
来比较字符串,因为C不是JavaScript,==
对其操作数进行数值比较。而不是
if (temp == temp2)
你应该写
if (strcmp(temp, temp2) == 0)
(并重新阅读一个好的 C 教程 - 在一个体面的教程中,肯定包括像这样的"棘手"东西。