Reputation: 91
I am trying to pull characters from a specific column (in this case, 0) of a text file, and load them into a vector. The code seems to work ok, until it reaches the end, when I get a "string subscript out of range" error, and I do not know how to fix this. Does anyone know what I can do? Here is the relevant code.
class DTree
{
private:
fstream newList;
vector<string> classes;
public:
DTree();
~DTree();
void loadAttributes();
};
void DTree::loadAttributes()
{
string line = "";
newList.open("newList.txt");
string attribute = "";
while(newList.good())
{
getline(newList, line);
attribute = line[0];
classes.push_back(attribute);
}
}
Upvotes: 0
Views: 228
Reputation: 1975
You can also try something like
ifstream ifs("filename",ios::in);
string temp;
getline(ifs,temp)// Called as prime read
while(ifs)
{
//Do the operations
// ....
temp.clear();
getline(ifs,temp);
}
ifs.clear();
ifs.close();
This works for almost all kinds of files.You can replace getline(ifs,temp)
by get()
function or by >>
operator based on your requirements.
Upvotes: 0