Search code examples
c++arraysfilestream

Reading from a text file to populate an array


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.


Solution

  • 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