Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Two Numbers Entered as Strings in Textfields

I have two text fields in which numbers are inputed as strings. I need to convert the strings to numbers, add them together and then display the result in a 3rd textfield.

I am totally new to iPhone programming .. So please don't be hard on me :P

Ok here is the problem

AdditionViewController.h

#import <UIKit/UIKit.h>

@interface AdditionViewController : UIViewController 
{
    IBOutlet UITextField *Number1;
    IBOutlet UITextField *Number2;
    IBOutlet UITextField *SumAnswer;
}

@property (retain, nonatomic) UITextField *Number1;
@property (retain, nonatomic) UITextField *Number2;
@property (retain, nonatomic) UITextField *SumAnswer;
-(IBAction)buttonPressed1:(id)sender;

@end

AdditionViewController.m

#import "AdditionViewController.h"

    @implementation AdditionViewController
    @synthesize Number1;
    @synthesize Number2;
    @synthesize SumAnswer;


    -(IBAction)buttonPressed1:(id)sender
    {
        SumAnswer.text = Number1.text + Number2.text; 
           // I want the above line to be edited so that I can get the addition
             of both the numbers in the 3rd Text Field 
    }

    -
    -
    -
    -
    -
    @end

I am really new to iPhone programming .. I am trying to understand how NSString can be used here .. But I am finding it a bit complicated .

If someone please tell me what the code should be ... It will be a great help . I have to submit a mini project to my school asap .

Thanking You , int3rc3pt0r

like image 306
Omkar Jadhav Avatar asked Dec 06 '22 03:12

Omkar Jadhav


1 Answers

NSString has method allowing to get numeric value from it (e.g. intValue, floatValue etc) - you can use them to convert string to numbers. To convert numbers to string you can use stringWithFormat: method - the way it takes format specifiers is similar to printf function in c.

-(IBAction)buttonPressed1:(id)sender
{
    // You may also need to check if your string data is a valid number
    int result = [Number1.text intValue] + [Number2.text intValue];
    SumAnswer.text = [NSString stringWithFormat:@"%d", result];
}
like image 174
Vladimir Avatar answered Dec 07 '22 16:12

Vladimir