0

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);
}
}
nym_kalahi
  • 91
  • 1
  • 2
  • 9
  • 3
    Are you sure `line` was read ok? If so, how are you sure? – chris Dec 07 '12 at 01:53
  • `line` must be empty(size() == 0), does your file start with a blank line? [`std::getline`](http://www.cplusplus.com/reference/string/getline/) reads until the first '\n' or new line character – Karthik T Dec 07 '12 at 01:55
  • @KarthikT, You mean a blank line, but same idea. – chris Dec 07 '12 at 01:55
  • I agree with chris, you should check line.size() > index before accessing line[index]. – Mike Trusov Dec 07 '12 at 01:57
  • And along with that, you should check the input operation to ensure it succeeded. Don't forget checking to make sure the file opened as well. – chris Dec 07 '12 at 01:57
  • @chris Yes, I am sure that it is read ok. I can see it when I put a break point in the while loop. It successfully gets each line, from what I can see. (I didn't check all 5000+, but I assume it's the same?) – nym_kalahi Dec 07 '12 at 02:00
  • It's possible that the final line is read in correctly, in which case `ios::good()` will return true (causing the code to re-enter the loop), but a subsequent read (`getline`) after that will have `line` be an empty string. – Chad Dec 07 '12 at 02:02
  • @chris The file opens correctly, and it does load characters into the vector (at first). – nym_kalahi Dec 07 '12 at 02:03
  • 1
    just try while(getline(newList, line) instead of checking for 'good' – Chubsdad Dec 07 '12 at 02:05
  • @Chubsdad I didn't realize you could do that. That appears to have fixed it! Thank you very much :] – nym_kalahi Dec 07 '12 at 02:07

2 Answers2

3

Please try 'while(getline(newList, line)'

Refer here

Community
  • 1
  • 1
Chubsdad
  • 24,777
  • 4
  • 73
  • 129
0

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.

Recker
  • 1,915
  • 25
  • 55