输出中文字符而不是数字?目标C.

时间:2012-05-03 04:05:55

标签: objective-c

它应该做什么:输入所有数字的输入字符串组,并在每次将新字符附加到NSMutableString编号时打印出来。然后,如果当前char不是数字,则检查它是+或x,还是*, - 。如果它是其中之一,那么它将它附加到数组并打印出来。

它做什么:输出中文

`Please enter math: 12+56x45
2012-05-02 23:52:06.538 CALC[1921:403] 퀱 
2012-05-02 23:52:06.541 CALC[1921:403] 퀱퀲 
2012-05-02 23:52:06.542 CALC[1921:403] running array (
"+"
)
2012-05-02 23:52:06.543 CALC[1921:403] 퀱퀲퀵  
2012-05-02 23:52:06.544 CALC[1921:403] 퀱퀲퀵퀶 
2012-05-02 23:52:06.544 CALC[1921:403] 퀱퀲퀵퀶큸 
2012-05-02 23:52:06.545 CALC[1921:403] 퀱퀲퀵퀶큸퀴 
2012-05-02 23:52:06.546 CALC[1921:403] 퀱퀲퀵퀶큸퀴퀵`

问题:我认为它与unichar char current = [InputString characterAtIndex:i];有关,但是当我运行没有else if部分的代码时,它可以正常工作。正如您所看到的那样,作为字符串一部分的字符数是预期的数字,问题似乎是它们使用了错误的语言。

我的代码:

int main ()
{
    char userInput[99];
    NSMutableString *number = [NSMutableString string];
    int i;

    printf( "Please enter math: " );

    scanf( "%s", userInput );
    fpurge( stdin );
    NSString *InputString = [NSString stringWithUTF8String:userInput];
    NSMutableArray *broken = [NSMutableArray array];

    for (i=0; i < [InputString length]; i++) {
        char current = [InputString characterAtIndex:i];
        NSString *cur = [NSString stringWithFormat:@"%c" , current];
        if (isalnum(current)) {
            [number appendString:[NSString stringWithCharacters:&current length:1]];
            NSLog(@"%@", number);
        }
        else if (current == '+'|| current == 'x'||current == '*'||current == '-') { 
            [broken addObject:[NSString stringWithFormat:cur]];
            NSLog(@"running array %@", broken);
        }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

我发现您已将char“转换”为NSString。为什么不尝试将cur附加到要打印的字符串上?所以改变:

[number appendString:[NSString stringWithCharacters:&current length:1]]

为:

[number appendString:cur]

答案 1 :(得分:1)

这可能是一种更高级别的方法,可以将您的数字与运算符分开,这样您就可以更轻松地处理您想要执行的数学运算......

NSString *equation = @"12+56x45";
NSCharacterSet *operatorCharacterSet = [NSCharacterSet characterSetWithCharactersInString: @"+-/x"];
NSCharacterSet *numberCharacterSet = [NSCharacterSet characterSetWithCharactersInString: @"1234567890"];

NSArray *numbersOnly = [equation componentsSeparatedByCharactersInSet: operatorCharacterSet];
NSArray *operatorsOnly = [equation componentsSeparatedByCharactersInSet: numberCharacterSet];

for (NSString *number in numbersOnly) {
    NSLog(@"%@", number);
}

for (NSString *operator in operatorsOnly) {
    NSLog(@"%@", operator);
}

结束位只记录数字和运算符,以显示它们现在如何分成不同的数组。这会使你的任务变得微不足道,但是如果你假设等式中的第一个数据是一个数字,你可以简单地遍历两个数组并进行数学运算。