首页 > 解决方案 > 编译“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];
}

标签: c++visual-studiocodeblocksdev-c++

解决方案


更改fopenfopen_s

像这样:errno_t err = fopen_s(&f, "myfile2.txt", "rb");


推荐阅读