Reading File into a vector

Hi,

So I've been trying to read a txt file into a vector. But I can't get it work. The program will start up but then just freeze. Can anyone tell me whats wrong?


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

using namespace std;

int main()
{
ifstream File;
vector<int> itemID;
int index;
int size = 5;

File.open("itemID.txt");

for(index = 0; index < size; index++)
File >> itemID[index];

for(index = 0; index < size; index++)
cout << itemID[index];

system("PAUSE");
return 0;
}


At the beginning the vector itemID has the size 0 hence trying to read data into that 0 vector will fail.

do this: vector<int> itemID(size); to get a vector that has the expected size.

See http://www.cplusplus.com/reference/stl/vector/


By the way: are you sure that "itemID.txt" can be opened (use is_open())? I'd suggest to use an absolute path (like "c:\\temp\\itemID.txt" (notice the "\\" for windows))

See http://www.cplusplus.com/reference/iostream/ifstream/
Topic archived. No new replies allowed.