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

在新的C ++代码中,我倾向于使用C ++ iostream库而不是C stdio库。


我注意到有些程序员似乎坚持使用stdio,坚持认为它更具可移植性。


真的是这样吗?有什么更好用的?


三国纷争
浏览 471回答 3
3回答

潇潇雨雨

型安全的。因此,分配给对象也明确检查了分配对象的类型(在编译时)(如果需要,则生成编译时错误)。这样可以防止运行时内存溢出或将浮点值写入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{&nbsp; // this structure reverse engineered from&nbsp; &nbsp;// example provided by 'Mikael Jansson' in order to make this a running example&nbsp; &nbsp; char*&nbsp; &nbsp; &nbsp; &nbsp;name;&nbsp; &nbsp; double&nbsp; &nbsp; &nbsp; mean;&nbsp; &nbsp; int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sample_count;};int main(){&nbsp; &nbsp; X&nbsp; &nbsp;stats[] = {{"Plop",5.6,2}};&nbsp; &nbsp; // nonsense output, just to exemplify&nbsp; &nbsp; // stdio version&nbsp; &nbsp; fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stats, stats->name, stats->mean, stats->sample_count);&nbsp; &nbsp; // iostream&nbsp; &nbsp; std::cerr << "at " << (void*)stats << "/" << stats->name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; << ": mean value " << std::fixed << std::setprecision(3) << stats->mean&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; << " of " << std::setw(4) << std::setfill(' ') << stats->sample_count&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; << " samples\n";&nbsp; &nbsp; // iostream with boost::format&nbsp; &nbsp; std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; % stats % stats->name % stats->mean % stats->sample_count;}

繁星coding

太冗长了。考虑iostream构造以执行以下操作(对于scanf同样):// nonsense output, just to examplifyfprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",&nbsp; &nbsp; stats, stats->name, stats->mean, stats->sample_count);那将需要类似:std::cerr << "at " << static_cast<void*>(stats) << "/" << stats->name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; << ": mean value " << std::precision(3) << stats->mean&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; << " of " << std::width(4) << std::fill(' ') << stats->sample_count&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; << " samples " << std::endl;字符串格式化是一种情况,在这种情况下,可以并且应该避免面向对象,而倾向于嵌入字符串中的格式化DSL。考虑一下Lisp format,Python的printf样式格式或PHP,Bash,Perl,Ruby及其字符串内插。iostream 对于该用例而言,充其量是错误的。

开心每一天1111

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