c++c++17freopen

C++: freopen (and I/O) just refuses to work


Today I'm having issues with my code. It appears that I can not get anything from input (whether file or stdin) as well as unable to print (whether from file or stdout). My code can have a lot of issues (well, this is code for a competitive programming problem, don't expect it to be good. It will be straight up horrendous and violate everything you know about C++).

#include <bits/stdc++.h>
#include <climits>
#include <vector>
using namespace std;
#define mp make_pair
#define endl "\n"
#define ll long long
#define ld long double 
const int nm = 1e3 + 1;
const int mod  = 1e9 + 7;
void fastio(string fi, string fo){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    if (fi.length() > 0){
        freopen(fi.c_str(), "r", stdin);
    }
    if (fo.length() > 0){
        freopen(fo.c_str(), "w", stdout);
    }
}

int m, n;
int demsm(int k, int p){
    int c = 0, r = p;
    while (r <= k){
        c += int(k / r);
        r *= p;
    }
    return c;
}

vector<pair<int, int>> uoc(int x){
    vector<pair<int, int>> u;
    for (int i = 2; x != 1; i++){
        int c = 0;
        while (x % i == 0){
            c++;
            x /= i;
        }
        u.emplace_back(mp(i, c));
    }
    return u;
}

int main(){
    fastio("", "");
    cin >> n >> m;
    cout << n << " " << m << endl;
    auto snt = uoc(m);
    for (auto i : snt){
        cout << i.first << " " << i.second << endl;
    }
    int a = 1e9;
    for (auto i : snt){
        a = min(a, demsm(n, i.first) / i.second);
    }
    cout << a << endl;
}


Solution

  • This isn't an issue with freopen or I/O. Here a = min(a, demsm(n, i.first) / i.second); You are dividing by zero and this results a segmentation error.

    The reason why the program isn't printing anything is because of the way how these lines work.

    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    

    You can read about them in this question.