hi all,
ive got this problem, i think it is an interplay of ifstream and vector...
the following code compiles and links without problem, but when i debug i get the message "expression: vector subscript out of range". i know that "out of range" means i am trying to access something which isnt there, and it is true that the element i am trying to access (in the line *here*) isnt there. the point is i dont understand why! if i take the line with *here* out of the code, it reads from the file, and the cout-loop shows the four words. but when i put the *here* line in, it never couts anything! i am very confused how that line, which is AFTER the cout loop, can affect it, or rather what is even earlier (the reading from the file, which enables the cout loop).
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(){
ifstream ifs;
ifs.open("file.txt");
string tok;
vector<string> vtoks;
while (getline(ifs,tok)){
vtoks.push_back(tok);
}
// vtoks.push_back("daimler");
// vtoks.push_back("volkswagen");
// vtoks.push_back("bmw");
// vtoks.push_back("daimler");
for (int i=0; i<vtoks.size(); i++){
cout << vtoks[i] << " ";
}
cout << endl;
cout << vtoks[0]; //**************here*******************
return 0;
}
the file "file.txt" contains four lines, no spaces:
daimler
volkswagen
bmw
daimler
i suspect the error is an interplay of the reading from the file and the vector accession, because if i comment out the while loop and uncomment the four push_back lines, it works fine.
any help is appreciated a lot.
richard