答复: [cpp] 关于STL中string的问题

Wu Yongwei adah at sh163.net
Sun Mar 5 18:21:36 CST 2006


呵呵,此处同意。vector加printf,又低效又不安全,两处没捞好。

不过,要注意_snprintf和itoa都不是跨平台的标准函数。一般而言,使用
snprintf(没有下划线)哪儿都行。还有,第二个常数32我认为写sizeof buf比较好。

吴咏炜

analyst wrote:

> 为什么都喜欢用这么麻烦而且低效的东西,不要为了用C++而用C++,别忘了还有C
>   char buf[32];
>   _snprintf(buf, 32, "%d", 10);//或者用itoa(10, buf, 10);
>   string str = buf;
>  
> 
>  
> 在06-3-3,*千里马肝* <oiramario at gmail.com <mailto:oiramario at gmail.com>> 
> 写道:
> 
>     例码:
>       std::vector<char> buf(buffer_size, 0);
>       _snprintf(&buf[0], buffer_size, "%d\0", 10);
>       // 赋值给字符串
>       std::string str = &buf[0];
>       MessageBox(NULL, str.c_str(), NULL, MB_OK);
>     好处:
>         1. 使用std::vector避免手动new/delete
>         2. 使用stl可以 充分利用stl的alloc(如stlport的memory pool)
>         3. 使用_snprintf防止溢出
>         4. std::string = std::vector(安逸:)
> 
>         -----原始邮件-----
>         *发件人:* cpp-bounces at codingnow.com
>         <mailto:cpp-bounces at codingnow.com> [mailto:
>         cpp-bounces at codingnow.com <mailto:cpp-bounces at codingnow.com>]*代
>         表 *苏益ꪏ
>         *发送时间:* 2006年3月2日 14:54
>         *收件人:* cpp at codingnow.com <mailto:cpp at codingnow.com>
>         *主题:* [cpp] 关于STL中string的问题
> 
>         请先看这段代码。
>         ----------------------------------------------------------------
>         //我希望把string赋值10,然后显示
>         string Buffer;
>         sprintf( Buffer.begin (),"%d",10);
>         MessageBox(NULL,Buffer.begin(),NULL,MB_OK);
>         ----------------------------------------------------------------
> 
>         建个程序,编译它,是通不过的。原因是Buffer没有初值,调用
>         Buffer.begin()返回是NULL,第三句用MessageBox弹出一个NULL的字符
>         串,这是不可取的。
> 
>         所以我改正以后,程序为
>         ---------------------------------------------------------------
>         //改正后的程序
>         string Buffer = "a"; //我随便给了个初值
>         sprintf( Buffer.begin(),"%d",10);
>         MessageBox(NULL,Buffer.begin (),NULL,MB_OK);
>         ----------------------------------------------------------------
>         但是,上面这段程序,可读性能差。别人会想:作者为什么给个"a"而不
>         是"b"呢?
> 
>         所以我想请教大家:
>         (1)这问题有没有更好的方法?最好不要MFC,也不用char数组,因为整
>         个程序中其它地方我都用了string。
>         (2)STL为什么这么设计?
>         难道定义Buffer以后,还没有分配空间?如果已经有空间,为什么不用
>         Begin()返回首个字符的地址?这样做意义呵在?



More information about the Cpp mailing list