1

The goal I am going for is to store values into a text file, and then populate an array from reading a text file.

At the moment, I store values into a text file;

Pentagon.CalculateVertices();//caculates the vertices of a pentagon

ofstream myfile;
myfile.open("vertices.txt");
for (int i = 0; i < 5; i++){
    myfile << IntToString(Pentagon.v[i].x) + IntToString(Pentagon.v[i].y) + "\n";
}
myfile.close();

I have stored the values into this text file, now I want to populate an array from the text file created;

for (int i = 0; i < 5; i++){
    Pentagon.v[i].x = //read from text file
    Pentagon.v[i].y = //read from text file
}

this is all I have for now; can someone tell me how you can achieve what the code says.

1 Answer 1

3

You don't need to convert int to std::string nor char*.

myfile << Pentagon.v[i].x << Pentagon.v[i].y << "\n";
// this will add a space between x and y coordinates

Read like this:

myfile >> Pentagon.v[i].x >> Pentagon.v[i].y;

<< and >> operators are the basics of streams, how come you haven't come across it?

You could also have a custom format, like [x ; y] (spaces can be omitted).

Writing:

myfile << "[" << Pentagon.v[i].x << ";" << Pentagon.v[i].y << "]\n";

Reading:

char left_bracket, separator, right_bracket;
myfile >> left_bracket >> Pentagon.v[i].x >> separator << Pentagon.v[i].y >> right_bracket;

// you can check whether the input has the required formatting
// (simpler for single-character separators)
if(left_bracket != '[' || separator != ';' || right_bracket != ']')
    // error
Sign up to request clarification or add additional context in comments.

8 Comments

So in order for me to store values in a text file, they can be any 'type'? They do not need to be strings? I come from a background, where the basics were skipped.
They could accept even custom classes if you overload the operators.
That makes sense, or we would not be able to have complex programs. A question, ">>" is giving me errors., do I need
@Moynul Have you used std namespace etc?
@TalhaIrfan At the top I have 'using namespace std' to let the compiler know in advance.
|

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.