Archived

This topic is now archived and is closed to further replies.

com

Why wont my file be copied into an array?

Recommended Posts

this is isnt the actual code but this is basically what i want it to do at the moment:
  
#include <fstream.h>

int mapFile[2000];

int main()
{
        ifstream map("map.ar", ios::app);
	map >> mapFile;
	map.close();
return 0;
}
  
Now like i said that isnt the actual code but its the only relevent part of my question, basically the compiler says: error C2679: binary ''>>'' : no operator defined which takes a right-hand operand of type ''int [2000]'' (or there is no acceptable conversion) it works fine if i use a standard int but then what i wanted to do wouldnt work properly. I need to be able to call every single coord in the file: mapFile[0], mapFile[1] etc. Anyone know a way to fix this?

Share this post


Link to post
Share on other sites
Baaaaad idea. You generally shouldn''t use the >> operator of ifstreams.

For single char input you can use the get member function:

  
int i = 0;
while(map.get(mapFile[i]))
i++;


There also is a getline member function.

There is a chapter about iostreams in volume 2 of "Thinking in C++", which you can download at www.bruceeckel.com


"Reality is merely an illusion, albeit a very persistent one." (Albert Einstein)
My Homepage

Share this post


Link to post
Share on other sites
quote:
Original post by randomZ
Baaaaad idea. You generally shouldn't use the >> operator of ifstreams.


Oh? Why not?

If you're comfortable with the stl and more modern use of input streams you could do something like this to read in a file of ints:


    
#include <vector>
#include <algorithm>
#include <fstream>
#include <iostream>

std::vector<int> mapFile;

int main(int argv, char ** argv)
{
std::ifstream map("map.ar");
std::copy(std::istream_iterator<int>(map), std::istream_iterator<int>(), std::back_inserter(mapFile));
return 0;
}


Oh and to answer the question of why the original posted code doesn't work...
The code "map >> mapFile" is calling a function. You could read it as "map.sendInputTo(mapFile)" or something like that. There are overloaded versions of the function for various built-in types like int, float, double, and string. Their signatures would be like (these might not be 100% accurate):

istream& istream::operator >> (int someInt);
istream& istream::operator >> (float someFloat);
istream& istream::operator >> (double someDouble);
istream& istream::operator >> (string someString);

There is no overloaded version for arrays of ints, which would look like this:

istream& istream::operator >> (int * someIntArray);

There isn't because the function couldn't possibly know how large someIntArray is and might write past its bounds.

[edited by - Dobbs on December 26, 2002 5:58:38 PM]

Share this post


Link to post
Share on other sites