当我终于意识到问题是从多个线程调用 sscanf 时,我一整天都在调试一个随机错误。
我通过运行以下代码进行了确认,该代码在 Snow Leopard 上按预期工作,但在我的 iphone 上使用 os 3.1.2 产生了非常奇怪的结果。它在模拟器中也可以正常工作。
在 iPhone 上,解析后的数字将是字符串中使用的数字的某种随机组合。
如果有人可以检查这是一般问题还是我这边的错误,那将非常有帮助。
- (void)testIt
{
[NSThread detachNewThreadSelector:@selector(scanfTest) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(scanfTest) toTarget:self withObject:nil];
}
- (void)scanfTest
{
while (true)
{
float value = 0.0f;
sscanf("456", "%f", &value);
sscanf( "1.63", "%f", &value);
if (value != 1.63f)
NSLog(@"strange value is %f", value);
}
}
我做了一些进一步的检查,似乎只有浮点数是一个问题。
此代码有效
- (void)scanfTest4
{
while (true)
{
int year = 0;
int month = 0;
int day = 0;
sscanf("20090131", "%4d%2d%2d", &year, &month, &day);
sscanf("19840715", "%4d%2d%2d", &year, &month, &day);
if (year != 1984 || month != 7 || day != 15)
NSLog(@"bla");
}
}
并且此代码因相同的随机数字问题而失败
- (void)scanfTest4
{
while (true)
{
int year = 0;
int month = 0;
float day = 0.0f;
sscanf("20090131", "%4d%2d%2f", &year, &month, &day);
sscanf("19840715", "%4d%2d%2f", &year, &month, &day);
if (year != 1984 || month != 7 || day != 15.0f)
NSLog(@"bla");
}
}