【问题标题】:I've got a problem with c++ about <stdio.h> library?我有关于 <stdio.h> 库的 c++ 问题?
【发布时间】:2020-12-31 10:31:25
【问题描述】:

我正在为我的学校学习 C++。我正在使用 Visual Studio 编写 C++ 代码,我正在尝试编译此代码:


#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    freopen("cd.inp", "r", stdin);
    freopen("cd.out", "w", stdout);
    int a, b;
    while (true){
        cin >> a >> b;
        cout << a << ' ' << b;
        break;
    }
    fclose(stdin);
    fclose(stdout);
}

我遇到了这些错误:

严重性代码描述项目文件行抑制状态 错误 C4996 'freopen':此函数或变量可能不安全。考虑改用 freopen_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。详细信息请参见在线帮助。 clock_degrees F:\CODING\C++\clock_degrees\clock_degrees\clock_degrees.cpp 11

严重性代码描述项目文件行抑制状态 警告 C6031 忽略返回值:'freopen'。 clock_degrees F:\CODING\C++\clock_degrees\clock_degrees\clock_degrees.cpp 11

我现在该怎么办? 我也有一些关于 scanfprintf 而不是 freopen 的问题。我认为问题来自 库。

【问题讨论】:

  • 你现在应该做的,实际上是使用 C++ 而不是 C。freopen 是一个 C 库函数,并不总是指定 C 库的标准输入/输出函数对 @ 有何影响987654323@ 和std::cout。即使您解决了此编译器诊断问题,这也可能有效,也可能无效。您应该查看如何使用std::ifstreamstd::ofstream,以便打开从文件读取或写入的流,并使用它而不是std::cinstd::cout,通过freopen 劫持底层文件流.附言scanfprintf 也是 C。
  • 您需要从其他地方获取 C++ 编码示例。这是 C 和 C++ 的混搭。学习 C++ 已经够难的了。
  • 不相关说明:在 C++ 中,如果您坚持使用 C 函数,则应使用 #include &lt;cstdio&gt; 而不是使用已弃用的“stdio.h”。
  • 很酷,有人删除了我的评论,到目前为止,这是唯一真正有帮助的评论,而不是人们讲述 c 和 c++ 头文件如何不混合的故事......
  • 建议您在格式化提取时添加错误检测/处理。此外,'cin' 是一个流(即 c++)... freopen 处理文件(c 风格)。

标签: c++ visual-studio compiler-errors stdio


【解决方案1】:

您应该改用ifstreamofstream

#include <fstream>

// don't do using namespace std;
using std::ifstream;
using std::ofstream;
using std::ios_base;

int main() {
  ifstream in;
  ofstream out;
  in.exceptions(ios_base::failbit | ios_base::badbit);
  out.exceptions(ios_base::failbit | ios_base::badbit);
  try {
    in.open("cd.inp");
    int a, b;
    // The while loop is pointless
    in >> a >> b;
    out.open("cd.out");
    out << a << ' ' << b;
  } catch (ios_base::failure const& e) {
    // Error handling 
    return -1;
  } 
}

【讨论】:

    【解决方案2】:

    我建议你可以在顶部添加#define _CRT_SECURE_NO_WARNINGS。如果使用freopen,编译器会认为不安全。所以,我建议你可以使用freopen_s

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2011-04-09
      相关资源
      最近更新 更多