简体   繁体   English

Objective C字符数组问题

[英]Objective C Char Array Issue

Hey guys so I'm trying to learn objective c as an independent study for my school and one of my projects just to practice is making a calculator program where the user inputs a string of numbers and operators and the program breaks it apart and does the calculation. 大家好,我想以此为目标来学习目标c,这是我学校的一项独立研究,我要练习的一个项目是制作一个计算器程序,用户在其中输入一串数字,运算符将其分解,然后执行计算。 Right now I have the input and I'm trying to have it find the operators and put them all in an array so that it can sort them to find order of operations and use the indices to find the different terms; 现在,我有了输入,并且我试图让它找到运算符并将它们全部放入一个数组中,以便它可以对它们进行排序以找到操作顺序,并使用索引来找到不同的术语。 however, when I try to print out the array to see if its holding the chars, it outputs some weird symbols like the apple logo or an upside down question mark. 但是,当我尝试打印该数组以查看其是否包含字符时,它会输出一些奇怪的符号,例如苹果徽标或颠倒的问号。 I've made an SSCCE of my problem -- does anyone know whats going on? 我已对我的问题进行了SSCCE -有人知道发生了什么吗?

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

    NSString *calculation;
    char str[50] = {0};
    int count = 0;

    NSLog(@"What would you like to calculate?");
    scanf("%s", str);
    calculation = [NSString stringWithUTF8String:str];

    for (int i = 0; i < [calculation length]; i++) {
        NSRange range = NSMakeRange (i, 1);
        if([[calculation substringWithRange: range] isEqualToString: @"*"] ||
           [[calculation substringWithRange: range] isEqualToString: @"/"])
            count++;
    }

    char operators[count];
    for (int i = 0; i < count; i++) {
        for (int j = 0; j < [calculation length]; j++) {
            NSRange range = NSMakeRange (j, 1);
            NSString *s = [s initWithString:[calculation substringWithRange: range]];
            if([s isEqualToString:@"*"]){
                operators[i] = '*';
                break;
            }
            if([s isEqualToString:@"/"]){
                operators[i] = '/';
                break;
            }
        }
        NSLog(@"%c", operators[i]);
    }

}
return 0;
}

To answer your question about what is going on in your code. 回答有关代码中正在发生什么的问题。 The "weird symbols" you are seeing are the un-initialized values in memory at your operators[] array. 您看到的“怪异符号”是operators[]数组中内存中的未初始化值。

To see the reason the char[] is left with garbage values look at this section of your code: 要查看char []留下垃圾值的原因,请查看代码的这一部分:

    ...
    NSString *s = [s initWithString:[calculation substringWithRange: range]];
    if([s isEqualToString:@"*"]){
        operators[i] = '*';
        break;
    }
    ...

You are sending initWithString to s . 您发送initWithStrings s is not yet allocated. s还没有分配。 This results in s being a nil . 这导致s nil And since sending a message like isEqualToString: to a nil will essentially evaluate NO even when an @"*" is in that range your assignment to operators[i] will never happen. 并且,由于将isEqualToString:类的消息发送到nil即使@"*"处于该范围内,也基本上不会评估为NO ,您对operators[i]分配将永远不会发生。

Easy fix though, just replace the s assignment with this: 不过,很容易解决,只需将s分配替换为:

NSString *s = [calculation substringWithRange:range];

You don't need anything fancy for this. 您不需要任何花哨的东西。 But: use stuff for what it is there for. 但是:请使用它的用途。

#import <Foundation/Foundation.h>

int main()
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    char str[128];
    printf("Enter formula:\n");
    scanf("%s", str); // this is DAMN unsafe, btw

    NSMutableArray *arr = [NSMutableArray array];

    char *s = str;
    while (*s) {
        if (*s == '*') {
            [arr addObject:@"*"];
        } else if (*s == '/') {
            [arr addObject:@"/"];
        }
        s++;
    }
    printf("\n");

    [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"%@", obj);
    }];

    [pool drain];
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM