如何让scanf在if语句中运行c

时间:2014-09-02 22:10:50

标签: objective-c if-statement scanf

如何在if语句中使scanf工作?在目标 - c

    Calculator *myCalculator = [ [ Calculator alloc ] init ] ;

    NSLog(@"What would you like to do: add , subtract, multiply , divide , set accmulator, or exit?") ;
    scanf("%c",  &what[20] ) ;

     if( strcmp(&what[20] , "subtract" ) == 0 )
    {
        NSLog(@"first number:" ) ;
        scanf("%lg" , &value1) ;
        NSLog(@"second number: ") ;
        scanf("%lg" , &value2) ;

        [myCalculator setAccmulator: value1] ;
        [myCalculator subtract: value2] ;
        NSLog(@"%lg" ,[myCalculator accmulator ]) ;
    }
    if( strcmp(&what[20] , "add" ) )
    {
        NSLog(@"first number:" ) ;
        scanf("%lg" , &value1) ;
        NSLog(@"second number: ") ;
        scanf("%lg" , &value2) ;

        [myCalculator setAccmulator: value1] ;
        [myCalculator add: value2] ;
        NSLog(@"%lg" ,[myCalculator accmulator ]) ;

    }
     if( strcmp(&what[20] , "multiply" ) == 0 )
    {
        NSLog(@"first number:" ) ;
        scanf("%lg" , &value1) ;
        NSLog(@"second number: ") ;
        scanf("%lg" , &value2) ;

        [myCalculator setAccmulator: value1] ;
        [myCalculator multiply : value2 ] ;
         NSLog(@"%lg", [myCalculator accmulator ]) ;
    }
     if( strcmp(&what[20] , "divide" ) == 0 )        {
        NSLog(@"first number:" ) ;
        scanf("%lg" , &value1) ;
        NSLog(@"second number: ") ;
        scanf("%lg" , &value2) ;

        [myCalculator setAccmulator: value1] ;
        [myCalculator divide: value2] ;
         NSLog(@"%lg", [myCalculator accmulator ]) ;
    }
     if( strcmp(&what[20] , "set accmulator" ) == 0 )        {
        NSLog(@"enter number you want to set" ) ;
        scanf("%lg" , &value1) ;

        [myCalculator setAccmulator: value1 ] ;
        NSLog(@"%lg" , [myCalculator accmulator] ) ;
    }
    else
        return 0 ;



}

return 0 ;

}

并且输出甚至没有给你一个机会为scanf键入任何内容,我已经尝试删除{}但它没有任何区别。

1 个答案:

答案 0 :(得分:0)

你的问题在这里:

( strcmp(&what[20] , "subtract" )。这不是一个方法结果,因此if语句不知道这是什么,因此它不知道如何处理== 0

尝试这种方式:

Calculator *myCalculator = [ [ Calculator alloc ] init ] ;

scanf("%c",  &what[20] ) ;

NSString* userInput = [[NSString alloc] initWithUTF8String: &what[20]];
//change "add" to check another NSString
//this way tou don't have to worry wether it's uppercase or lowercase
if ([userInput caseInsensitiveCompare:@"subtract"]==NSOrderedSame) 
{
//check if negative then do whatever
}

NB: ==比较字符串的引用(地址),而不是它们的值。