Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Implement ofstream of high.txt File in C++

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 456
    Answer it

    I want to output a score in a file high.txt that is highest among the previous score (It is actually a guessing game) but everytime i run this code it outputs 1 as the highest score (it should be no of time i guess for example if i guess the random no 5 times it would output 5 and the next time I compile and run it and if i guess it in 1 chance it should output 1).

     

    #include<iostream>
    #include<ctime>
    #include<cstdlib>
    #include<string>
    #include<vector>
    #include<array>
    #include<fstream>
    using namespace std;
    void print_vec(vector<int>vector)
    {
        for(int i=0;i<vector.size();i++)
        {
            cout<<vector[i]<<"\t";
        }cout<<"\n";
    }
    void play()
    {
    vector<int> guesses;
        int g_count=0;
        int random=rand()%251;
        cout<<random<<"\n";
        cout<<"Guess a no";
        while(true)
        {
            int guess;
            cin>>guess;
            g_count++;//g_count++
            guesses.push_back(guess);
            if(guess==random)
            {
                cout<<"You win hurray\n";
                break;
            }
            else if(guess<random)
            {
                cout<<"too low\n";
            }
            else
            {
                cout<<"too high\n";
            }
    ifstream input ("high.txt");

    input.is_open();
    if(!input.is_open())
    {
        cout<<"Unable to open file\n";
        return;
    }
    int scoring;
    input>>scoring;
    ofstream output("high.txt",ios::out);
    if(!input.is_open())
    {
        cout<<"Unable to open file\n";
        return;
    }
    if(g_count<scoring)
    {
        output<<g_count;
    }
    else
    {
        output<<scoring;
    }
        }print_vec(guesses);
    }
    int main()
    {
        srand(time(NULL));
        int choice;
        do
        {
            cout<<"\n 0. Quit"<<"\n 1. Play \n";
            cin>>choice;
        switch(choice)
        {
        case 0:
            cout<<"\n thanks for nothing";
            break;
        case 1:
            play();
        }
     }
     while(choice!=0);
    }
     

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: