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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't end up using your code, but I did get it to work. Thanks for your reply, though, Michael.
@user1637573:If your problem is solved, you should mark it as solved. This is sheer waste of time of others otherwise.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.