为了账号安全,请及时绑定邮箱和手机立即绑定

在C ++代码中应该使用哪个CI / O库?

在C ++代码中应该使用哪个CI / O库?

C++
三国纷争 2019-10-19 15:57:30
在新的C ++代码中,我倾向于使用C ++ iostream库而不是C stdio库。我注意到有些程序员似乎坚持使用stdio,坚持认为它更具可移植性。真的是这样吗?有什么更好用的?
查看完整描述

3 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

型安全的。因此,分配给对象也明确检查了分配对象的类型(在编译时)(如果需要,则生成编译时错误)。这样可以防止运行时内存溢出或将浮点值写入char对象等。


另一方面,scanf()/ printf()和family依赖程序员获取正确的格式字符串,并且没有类型检查(我相信gcc具有扩展名可以帮助您)。因此,它是许多错误的源头(因为程序员的分析能力不如编译器[更不用说编译器比人类更完美了])。


只是为了澄清Colin Jensen的评论。


自上一个标准发布以来,iostream库一直保持稳定(我忘了实际年份,但大约是10年前)。

澄清Mikael Jansson的评论。


他提到的其他使用格式样式的语言都有明确的保护措施,以防止C stdio库可能(在C语言中而不是在所提到的语言中)引起运行时崩溃的危险副作用。

注意:我同意iostream库有点冗长。但是我愿意忍受冗长的措辞以确保运行时安全。但是我们可以通过使用Boost Format Library减轻冗长。


#include <iostream>

#include <iomanip>

#include <boost/format.hpp>


struct X

{  // this structure reverse engineered from

   // example provided by 'Mikael Jansson' in order to make this a running example


    char*       name;

    double      mean;

    int         sample_count;

};

int main()

{

    X   stats[] = {{"Plop",5.6,2}};


    // nonsense output, just to exemplify


    // stdio version

    fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",

            stats, stats->name, stats->mean, stats->sample_count);


    // iostream

    std::cerr << "at " << (void*)stats << "/" << stats->name

              << ": mean value " << std::fixed << std::setprecision(3) << stats->mean

              << " of " << std::setw(4) << std::setfill(' ') << stats->sample_count

              << " samples\n";


    // iostream with boost::format

    std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n")

                % stats % stats->name % stats->mean % stats->sample_count;

}


查看完整回答
反对 回复 2019-10-19
?
繁星coding

TA贡献1797条经验 获得超4个赞

太冗长了。


考虑iostream构造以执行以下操作(对于scanf同样):


// nonsense output, just to examplify

fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",

    stats, stats->name, stats->mean, stats->sample_count);

那将需要类似:


std::cerr << "at " << static_cast<void*>(stats) << "/" << stats->name

          << ": mean value " << std::precision(3) << stats->mean

          << " of " << std::width(4) << std::fill(' ') << stats->sample_count

          << " samples " << std::endl;

字符串格式化是一种情况,在这种情况下,可以并且应该避免面向对象,而倾向于嵌入字符串中的格式化DSL。考虑一下Lisp format,Python的printf样式格式或PHP,Bash,Perl,Ruby及其字符串内插。


iostream 对于该用例而言,充其量是错误的。


查看完整回答
反对 回复 2019-10-19
?
开心每一天1111

TA贡献1836条经验 获得超12个赞

该升压格式库提供了printf风格的字符串格式化一个类型安全的,面向对象的替代品,到不从通常的冗长的问题遭受输入输出流的补充,由于巧妙地利用运营商%。如果您不喜欢使用iostream的operator <<进行格式化,我建议您考虑使用纯C printf。


查看完整回答
反对 回复 2019-10-19
  • 3 回答
  • 0 关注
  • 468 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信