gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:36:31 26 4
gpt4 key购买 nike

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

我注意到一些程序员似乎坚持使用 stdio,坚持认为它更便携。

真的是这样吗?用什么比较好?

最佳答案

回答原问题:
可以使用 stdio 完成的任何事情都可以使用 iostream 库完成。

Disadvantages of iostreams: verbose
Advantages of iostreams: easy to extend for new non POD types.

C++ 在 C 基础上向前迈进的一步是类型安全。

  • iostreams 被设计成明确的类型安全。因此,对对象的赋值也显式检查了被赋值对象的类型(在编译器时)(如果需要,生成编译时错误)。从而防止运行时内存溢出或将浮点值写入 char 对象等。

  • scanf()/printf() 和另一方面依赖于程序员获取正确的格式字符串并且没有类型检查(我相信 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;
}

关于c++ - 在 C++ 代码中应该使用哪个 C I/O 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/119098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com