iOS 调试器在文本字段中输入 0.0 时崩溃
iOS Debugger Crashes When Inputting 0.0 In Textfield
我目前正在Xcode中开发iOS应用程序,我想出了计算有效位数的代码。它是用C++写的,但我做了一些更改来让它工作。每当我输入零值时,它都会崩溃,但其他任何东西都可以正常工作。
我的代码如下:
- (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 (text1.at(0) == '0' || text1.at(0) == '.')//Trim Leading Zeros...
{
text1 = text1.substr(1);
}
我相信这就是你的问题所在。测试字符串"0.0"仅包含 0 和 .字符。循环 3 次后,text1 是空字符串,但您仍在尝试访问第一个字符。
此行也可能不符合您的预期: if ([[文本字段文本] 双倍值] == 0.0)
任何不是数字的东西都会被转换为 0.0,所以[@"foo" doubleValue] == 0.0
也是如此。
这里还有很多其他问题,比如使用UTF8String。如果用户键入的不是低 ascii 字符,就会发生奇怪的事情。
你真的不需要在这里C++。仅使用目标 C 就很容易。
其他一些评论...你可能想要 if/else if/else if 而不是 3 个连续的 else。
最后一个 if 也可以很容易地从以下转换:
if ([[thetextfield text] doubleValue] == 0.0)
{
newLength = 1;
NSString *zeroVal = [NSString stringWithFormat:@"%i", newLength];
self.display3.text = zeroVal;
}
自
if (...) {
self.display3.text = @"1";
}
相关文章:
- 虚幻引擎 3 游戏在 Steam 输入时崩溃
- 为什么这个程序在我插入前2个输入后崩溃
- C 程序仅在字符阵列获得“ 1000!”的输入时才在DELETE上崩溃
- 程序在 scanf( "%x" ,&foo) 上崩溃时尝试输入十六进制值
- 无效输入导致程序崩溃.有没有办法忽略它
- Pollard Rho 在不太大的输入上崩溃
- 当我输入12位数字时,为什么以下代码崩溃
- 用户输入可以超过数组的大小,但最终会崩溃
- Rcpp 函数在使用 "long" 输入时崩溃 R
- 我的使用地图的程序在第一次输入后崩溃
- 当我尝试输入值时程序崩溃
- 当输入大小足够大时,合并排序崩溃
- 程序在输入 10 个字符串后崩溃
- 当输入到结构点中的双指针数组时,程序崩溃
- 当我输入矩阵值时,为什么我的程序会崩溃
- 在opencv中发现凸性缺陷?[崩溃取决于给定的输入图像]
- 每当我输入长度为4的字符串时,下面的cpp代码就会崩溃(向量中的malloc失败)
- 当输入为高值时程序崩溃
- 暴力迫使程序以不同的输入崩溃的策略是什么?
- 输入崩溃(c++)