assignment

for(int k=0; k < 6; k++)

{
int x,y;
inLocn.open("locn1.dat");
inLocn >> x;
cout << x;
inLocn >> y;
cout << y;
p1.shipBoard[x][y];
inLocn.close();
}

The above code is part of an assignment. A battleships game including a struct. What I intended to do with this code is open a file and read its contents into a struct member when I run my program it doesn't return the contents of the file as I intended, rather, it returns a repetition of a sequence of numbers that are not in the file. Any help would be appreciated. I think maybe there is a more straight forward way to read numeric input from a file into an array.
You appear to be reading in two values and storing them in x and y, showing them to the operator with cout, and then doing nothing else with them. You haven't written any code to store them in any struct.
Thanks Moschops. I see what you mean. I changed the code to include the cout's so I could see on screen what was in x and y because I was getting unexpected results. I thought that because I had x and y in "p1.shipBoard[x][y];" that this would assign the values in x and y to "p1.shipBoard[x][y];".
The file stores a sequence of 12 digits, 6 pairs or x,y coordinates that I would like to read in from the file into "p1.shipBoard[x][y]; "
Do I need to do "inLocn>>p1.shipBoard[x][y];" or some such?
My problem, other than being a novice :-), is that I can't figure out how to read in pairs of digits from file to array.
I thought that because I had x and y in "p1.shipBoard[x][y];" that this would assign the values in x and y to "p1.shipBoard[x][y];".


Does int a; assign a value to a? No. Same thing here.

If you want to set the value of p1.shipBoard[x][y] , you can do it like this:
p1.shipBoard[x][y] = someValue;

If x and y are the positions where you want to store some value, what is the value you actually want to store?
The value I eventually want stored at p1.shipboard[x][y] is 'S'.
I have edited the line to read: p1.shipboard[x][y]='S';
the contents of the file at the moment is "010203040506" but the cout's show: "42773120" being read from the file. do I need to open the file in binary mode maybe?
There may be a problem in that you only read the first two values from the file as you open anc close the file within the for loop.

Open the file first, read in the data within the for loop then close the file.

The contents of the file will need a seperator between each number too, something like

01 02 03 04 05 06
Last edited on
So read it all in in one go rather than bit by bit as the for loop iterates.
cheers guys, I think that I can manage from here.
Topic archived. No new replies allowed.