免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 12894 | 回复: 2
打印 上一主题 下一主题

关于sprintf(),字符串补0的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-06-23 22:31 |只看该作者 |倒序浏览
在SCO下sprintf( ch_tmp, "%08s", "abc" );如果字符串不足8位,会自动补0 “00000abc”
但是在LINUX下是不可以的,变为“     abc”;
请知道的说下差异在哪里,怎么解决,谢谢了

论坛徽章:
0
2 [报告]
发表于 2008-06-23 22:40 |只看该作者
我觉得补0才有点奇怪。

论坛徽章:
0
3 [报告]
发表于 2008-06-23 23:33 |只看该作者
原帖由 cewei76 於 2008-6-23 22:31 發表
在SCO下sprintf( ch_tmp, "%08s", "abc" );如果字符串不足8位,會自動補0 「00000abc」
但是在LINUX下是不可以的,變為「     abc」;
請知道的說下差異在哪裡,怎麼解決,謝謝了


程式庫 (library) 實做不一樣。

先看 freebsd 的 sprintf manpage :


  1. `0' (zero)   Zero padding.  For all conversions except n, the converted value is padded on the left with zeros rather
  2.                     than blanks.  If a precision is given with a numeric conversion (d, i, o, u, i, x, and X), the 0 flag is ignored.
复制代码


linux 的 manpage :


  1. 0      The value should be zero padded.  For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the
  2.         converted value is padded on the left with zeros rather than blanks.  If the 0  and  -  flags  both
  3.         appear,  the  0 flag is ignored.  If a precision is given with a numeric conversion (d, i, o, u, x,
  4.          and X), the 0 flag is ignored.  For other conversions, the behavior is undefined.
复制代码


所以結果不一樣。

其次我個人使用 python 經驗,我測試過不管是 freebsd or linux,這段 code 輸出都是相同的。

Linux 機器:

  1. $ python
  2. Python 2.5.2 (r252:60911, Apr 15 2008, 16:58:19)
  3. [GCC 4.2.3 (4.2.3-6mnb1)] on linux2
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>>
  6. >>> str = "%08s"
  7. >>>
  8. >>> str % "abc"
  9. '     abc'
  10. >>>
复制代码


FreeBSD 機器:


  1. $  python
  2. Python 2.5.2 (r252:60911, Apr 28 2008, 13:43:01)
  3. [GCC 4.2.1 20070719  [FreeBSD]] on freebsd7
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> str = "%08s"
  6. >>>
  7. >>> str % "abc"
  8. '     abc'
  9. >>>
复制代码


所以沒有補上 0 這才算是正常的,因為那是字串而不是數值。

--
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP