C中的字符串格式化输出(2)

平台依赖
Mac OS X uses several data types—NSInteger, NSUInteger,CGFloat, and CFIndex—to provide a consistent means of representing values in 32- and 64-bit environments. In a 32-bit environment, NSInteger and NSUInteger are defined as int and unsigned int, respectively. In 64-bit environments, NSInteger and NSUInteger are defined as long and unsigned long, respectively. To avoid the need to use different printf-style type specifiers depending on the platform, you can use the specifiers shown in Table 2. Note that in some cases you may have to cast the value.

Table 2 Format specifiers for data types 类型   定义   建议  
NSInteger   %ld or %lx   Cast the value to long  
NSUInteger   %lu or %lx   Cast the value to unsigned long  
CGFloat   %f or %g   %f works for floats and doubles when formatting; but see below warning when scanning  
CFIndex   %ld or %lx   The same as NSInteger  
pointer   %p   %p adds 0x to the beginning of the output. If you don’t want that, use %lx and cast to long.  
long long   %lld or %llx   long long is 64-bit on both 32- and 64-bit platforms  
unsigned long long   %llu or %llx   unsigned long long is 64-bit on both 32- and 64-bit platforms  

The following example illustrates the use of %ld to format an NSInteger and the use of a cast.

1
2

 

NSInteger i = 42;
printf("%ld\n", (long)i);

 

In addition to the considerations mentioned in Table 2, there is one extra case with scanning: you must distinguish the types for float and double. You should use %f for float, %lf for double. If you need to use scanf (or a variant thereof) with CGFloat, switch to double instead, and copy the double to CGFloat.

1
2
3
4

 

CGFloat imageWidth;
double tmp;
sscanf (str, "%lf", &tmp);
imageWidth = tmp;

 

It is important to remember that %lf does not represent CGFloat correctly on either 32- or 64-bit platforms. This is unlike %ld, which works for long in all cases.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ppjfd.html