c++ - 编译“fopen_s”时出错未在此范围内声明
问题描述
VS 和 CODEBLOCKS 编译运行良好。当我尝试 Dev c++ 或Online GDB时出现错误。
// Ex7.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <fstream>
#include <string>
#include <list>
using namespace std;
//ASKISI 1
int getMedian(int arr[]);
//ASKISI 2
int main()
{
int arr[9];
for (int i = 0; i < 9; i++)
{
std::cout << "Enter num " << i << ": ";
std::cin >> arr[i];
}
std::cout << "\nMedian of array is: " << getMedian(arr) << "\n\n";
string line;
int len = 0;
ifstream myfile("myfile2.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
len += line.length();
}
myfile.close();
}
else
cout << "Unable to open file";
getchar();
int c;
cout << "\nEnter char: ";
c = getchar();
if (c == 101)
{
FILE* f;
fopen_s(&f, "myfile2.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
char* string = (char*)malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);
string[fsize] = 0;
int sum = 0;
int cnt = 0;;
int len = sizeof(string) / sizeof(*string);
for (int i = 0; i < len - 1; i++)
{
sum += string[i] + string[i + 1];
cnt++;
}
cout << "\nAverage 1+2nd: " << sum / cnt << "\n" << endl;
cnt = 0;
for (int i = 0; i < len - 2; i++)
{
sum += string[i] + string[i + 2];
cnt++;
}
cout << "\nAverage 1+3nd: " << sum / cnt << "\n" << endl;
cnt = 0;
for (int i = 0; i < len - 3; i++)
{
sum += string[i] + string[i + 3];
cnt++;
}
cout << "\nAverage 1+3nd: " << sum / cnt << "\n" << endl;
int i = 0, alphabet[26] = { 0 }, j;
while (string[i] != '\0')
{
if (string[i] >= 'a' && string[i] <= 'z')
{
j = string[i] - 'a';
++alphabet[j];
}
++i;
}
cout << "Frequency of all alphabets in the string is:" << endl;
for (i = 0; i < 26; i++)
cout << char(i + 'a') << " : " << alphabet[i] << endl;
ofstream fout("ex3.txt");
if (!fout)
{
cerr << "Could not open file." << endl;
return 1;
}
for (i = 0; i < 26; i++)
{
fout << char(i + 'a') << " : " << alphabet[i] << endl;
}
fout.close();
}
}
int getMedian(int arr[])
{
return arr[5];
}
解决方案
更改fopen
为fopen_s
。
像这样:errno_t err = fopen_s(&f, "myfile2.txt", "rb");
推荐阅读
- python-3.x - 将字符串列表解析为相应的对象
- javascript - 单击每一行时的css过渡
- apache-spark - 缓慢加入pyspark,尝试重新分区
- ansible - 如何从变量 ['vars'] 在 Ansible 查找插件中获取完全评估的变量值
- python-3.x - 从python3中的url打开一个gzip文件并使用islice
- node.js - 运行“heroku logs --tail”后无法输入
- telegram-bot - Telegram bot - 仅适用于我,但不适用于其他用户
- javascript - Jest 使用之前测试中加载的模块
- amazon-cognito - 我什么时候应该在 AWS Cognito 中使用 adminCreateUser 和 signUp
- flutter - 如何在flutter中自定义carousel_slider?