我对c ++有关<stdio.h>库有问题吗?

问题描述

我正在为学校学习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

我现在该怎么办? 我也遇到了有关 scanf printf 而不是 freopen 的问题。我认为问题可能来自库。

解决方法

您应该改用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;
  } 
}
,

我建议您可以在顶部添加#define _CRT_SECURE_NO_WARNINGS。如果使用freopen,则编译器会认为这是不安全的。因此,我建议您可以使用freopen_s

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...