2012-04-20 68 views
0

我目前正在使用Xcode的iOS應用程序,並且已經提出了用於計算有效位數的代碼。它是用C++編寫的,但我做了一些改變以使其起作用。每當我輸入一個零值,它崩潰,其他任何工作都很好。iOS調試器在文本框中輸入0.0時崩潰

我的代碼如下:

- (IBAction)sigFigCount:(UITextField *)thetextfield 
{ 
length = 0; 
if (thetextfield == _textfield1) 
{ 
    if ([thetextfield.text length] > 0)//If TextField Has More Than 0 digits... 
    { 
     text1 = std::string([_textfield1.text UTF8String]); 
     while (text1.at(0) == '0' || text1.at(0) == '.')//Trim Leading Zeros... 
     { 
      text1 = text1.substr(1); 
     } 
     length = text1.length(); 
     decimal = text1.find('.'); 
     if (decimal >= 0 && decimal < text1.length())//Dont count decimal as sig fig... 
     { 
      length -= 1; 
     } 
     if ([[_textfield1 text] doubleValue] == 0.0) 
     { 
      NSLog(@"HERE"); 
      self.display3.text = @"1"; 
     } 
     NSString *siggy = [NSString stringWithFormat:@"%i", length]; 
     self.display3.text = siggy; 
    } 
    if ([thetextfield.text length] == 0) 
    { 
     length = 0; 
     NSString *ifzero = [NSString stringWithFormat:@"%i", length]; 
     self.display3.text = ifzero; 
    } 
    if ([[thetextfield text] doubleValue] == 0.0) 
    { 
     newLength = 1; 
     NSString *zeroVal = [NSString stringWithFormat:@"%i", newLength]; 
     self.display3.text = zeroVal; 
    } 
    NSString *norm = [NSString stringWithFormat:@"%i", length]; 
    self.display3.text = norm; 
} 
} 

請幫幫忙,我相信它有事情做與數字在內存中表現的方式......但NSLog的工作時,我把它放在一個while語句...任何輸入讚賞。

謝謝

+0

什麼崩潰:

最後,如果也可以很容易地從轉換?崩潰日誌在哪裏? – 0x8badf00d 2012-04-20 03:14:57

+0

真的沒有崩潰日誌,它的輸出是「terminate called throwing an exception」並且iOS Simulator退出。 – JoeyLaBarck 2012-04-20 03:33:33

回答

0
while (text1.at(0) == '0' || text1.at(0) == '.')//Trim Leading Zeros... 
     { 
      text1 = text1.substr(1); 
     } 

我相信這是你的問題所在。您的測試字符串'0.0'僅包含0和。字符。經過循環3次後,text1是空字符串,但您仍然嘗試訪問第一個字符。

此行也可能不會做你所期望的: 如果([thetextfield文本]中的doubleValue] == 0.0)

什麼,這不是一個數字將被轉換爲0.0,所以[@"foo" doubleValue] == 0.0是真好。

這裏還有其他一些問題,比如使用UTF8String。如果用戶輸入的內容不是低級別的ASCII字符,就會發生奇怪的事情。

這裏真的不需要任何C++。只有客觀的C纔會很容易。

其他一些評論...你可能想要if/else if/else而不是僅僅連續3個elses。

if ([[thetextfield text] doubleValue] == 0.0) 
    { 
     newLength = 1; 
     NSString *zeroVal = [NSString stringWithFormat:@"%i", newLength]; 
     self.display3.text = zeroVal; 
    } 

if (...) { 
    self.display3.text = @"1"; 
} 
+0

謝謝Matt,我只有小數點,並且不允許除數字和小數點以外的任何字符。我在while循環'&& [_textfield1 text] doubleValue]!= 0.0)'中添加了語句,因此如果值爲零,它將不會執行while循環。但由於某種原因,如果我輸入0.00,則表示3 sig figs。我無法弄清楚爲什麼。 – JoeyLaBarck 2012-04-20 04:02:56