1

I know this question has been asked a million times before, but most of the questions are more complex than I need. I already know which lines will have what data, so I just want to load each line as its own variable.

For example, in "settings.txt":

800
600
32

And then, in the code, line 1 is set to int winwidth, line 2 is set to int winheight, and line 3 is set to int wincolor.

Sorry, I'm pretty new to I/O.

user1637573
  • 11
  • 1
  • 2

2 Answers2

3

Possibly the simplest thing you can do is this:

std::ifstream settings("settings.txt");
int winwidth;
int winheight;
int wincolor;

settings >> winwidth;
settings >> winheight;
settings >> wincolor;

However this will not ensure that each variable is on a new line, and doesn't contain any error handling.

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
0
#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::ifstream;
using std::string;

int main()
{
    int winwidth,winheight,wincolor;       // Declare your variables
    winwidth = winheight = wincolor = 0;   // Set them all to 0

    string path = "filename.txt";          // Storing your filename in a string
    ifstream fin;                          // Declaring an input stream object

    fin.open(path);                        // Open the file
    if(fin.is_open())                      // If it opened successfully
    {
        fin >> winwidth >> winheight >> wincolor;  // Read the values and
                           // store them in these variables
        fin.close();                   // Close the file
    }

    cout << winwidth << '\n';
    cout << winheight << '\n';
    cout << wincolor << '\n';


    return 0;
}

ifstream can be used with the extraction operator >> in much the same way you use cin. Obviously there is a lot more to file I/O than this, but as requested, this is keeping it simple.

derpface
  • 1,611
  • 1
  • 10
  • 20