Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Reading integers from a file in C++

  • 09-07-2009 06:38PM
    #1
    Closed Accounts Posts: 356 ✭✭


    This should be simple, don't know why it ain't working. I basically want to read some integers from a file storing them in variables i already have declared. If the file doesn't open i give the variables default values.
        std::ifstream inFile;
        inFile.open("options.txt");
        int nextInt;
        
        //If the file loaded
        if( !inFile )
        {
            noOfPlayers = 10;
            startingChips = 500;
            hands_per_level = 10;
            table = 3;
            deck = 3;
            AI = 3;
        }
        else{  
            inFile >> nextInt;
            noOfPlayers=nextInt;
            
            inFile >> nextInt;
            startingChips=nextInt;
            
            inFile >> nextInt;
            startingChips=nextInt;
            
            //Close the file
            inFile.close();
        }
    

    My text file is number space num e.g.:
    10 500 10
    but my variables are not getting filled with these numbers. It reads in the first number fine.


Comments

  • Closed Accounts Posts: 7,794 ✭✭✭JC 2K3


    Try inFile >> noskipws >> nextInt; instead.


  • Closed Accounts Posts: 356 ✭✭Mullicker


    Try inFile >> noskipws >> nextInt; instead

    Still no luck. Most tutorials i found have same code as mine so i can't figure out why its not working. Has anyone any suggestions?


  • Closed Accounts Posts: 7,794 ✭✭✭JC 2K3


    Your code works for me.

    Are you aware that :
    inFile >> nextInt;
    startingChips=nextInt;
    
    is duplicated?


  • Closed Accounts Posts: 356 ✭✭Mullicker


    Wow so dumb how did i miss that:eek:, thank you, works fine now. I was about to make a lot of changes to reading a comma separated file. Thank god for that:o


Advertisement