0

so here are my instructions to create a while loop to open a file called ‘G:/points.dat’

This is my code so far. I'm struggling to create the for loop that reads through the file, prints them to the monitor and then using those integers as x, y points. I can understand naming the x and y parameters, but im struggling with the loop itself

#include "Window.h"
#include "Colours.h"
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main(int argc, char * argv[]) {
// create a new window of size 500 x 500 pixels
// the top left corner of the window is (0,0)
    SPA::Window window(500,500,"My Test");
    ifstream myInputFile;
    string inputFileName = "G:/points,dat";

    myInputFile.open(inputFileName);

    int i = 0;
    myInputFile >> i;

    myInputFile.close();

    window.show(argc,argv);

    return Fl::run();
}
  • Open file ‘G:/points.dat’

  • Read in multiple pairs of numbers – ie two numbers per line until the end of the file

  • You should use a while loop and appropriate tests of the file state to detect the end of file

  • the eof flag only gets set to true after you have tried to read at least one value beyond the end of the file.
  • Each pair of numbers represents the x and y coordinates (x,y) of a point on a line to be drawn.
    • Inside your loop add a point to the current line for each (x,y) value you read in
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
thtcurlygirl
  • 67
  • 2
  • 6
  • You need a type that represents points and a collection of such points. – molbdnilo Feb 16 '18 at 18:53
  • After following molbdnilo's recommendation, [give Option 2 of this linked answer](https://stackoverflow.com/a/7868998/4581301) a read for ideas on how to load the point-containing type. Also worth [looking into creating a `>>` overload](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) for this type because it can turn the main program logic into a dead-stupid `while` loop. – user4581301 Feb 16 '18 at 19:12

1 Answers1

2

The loop is easy enough

while (myInputFile >> x >> y)
{
    // do something with x and y
    ...
}

That loop doesn't strictly read two values per line, it just reads the next two values whether they are on the next line or not.

BTW you have a typo in your code

string inputFileName = "G:/points,dat";

should be

string inputFileName = "G:/points.dat";

When you open a file you should always check to see if it opened successfully.

john
  • 85,011
  • 4
  • 57
  • 81