gpt4 book ai didi

c++ - 什么时候使用 printf/scanf vs cout/cin?

转载 作者:可可西里 更新时间:2023-11-01 17:39:32 25 4
gpt4 key购买 nike

我正在使用 MinGW 的 g++ 测试我在网上找到的一些片段。这是 C++ 编译器……为什么它能正确编译 C……为什么人们将 C 和 C++ 混为一谈。

具体问题是:可以吗?同时使用 C 和 C++ 并在 g++ 下编译。如果答案是肯定的,这会让我的生活变得轻松,因为我不必修改代码。

奇怪的是......为了让一些 C++ 工作,特别是当将字符串传递给 ifstream 构造函数时,它需要一个 C 类型的字符串......

我的猜测是,因为 C++ 有时依赖于 C 构造,所以可以将两种语言一起编写。

但是作为风格问题,您应该选择 cout/cinprintf/scanf

最佳答案

有一些奇怪的地方char*是需要的。您可以使用 .c_str() 弥合差距std::string 的方法得到一个。

在大多数情况下,C++ 的 C 子集是兼容的。在大多数情况下,究竟如何不兼容并不重要:

http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B

如果您在 C++ 编译器下编译 C 代码片段,请务必将其更改为在您的包含中使用“c”库格式...例如 #include <cstdio>而不是 #include <stdio.h>

Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?

关于 Bjarne 自己关于为什么要避免 scanf 的合理论证,请查看本文的开头:

http://www.stroustrup.com/new_learning.pdf

使用 iostreams 代替 printf 也有很多好处:

'printf' vs. 'cout' in C++

关于c++ - 什么时候使用 printf/scanf vs cout/cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7780072/

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