-5

I keep getting the error: Vector subscript out of range . I've spend an hour trying to find out why I keep getting it , it might be something obvious but I can't see it . From the trial and error trying to find out where is the problem I managed to narrow it down to the second while() but still . Any help is welcomed . Thanks.

fstream text("text.txt",ios::in);
vector <char> arr;
vector <int> freq;
char a;
if(!text) 
{
    cout<<"\nError!\n"<<endl;
    return;
}
else
{
    //-------------//initializing first element of each vector
    text>>a;
    arr.push_back(a);
    freq.push_back(1);
    //-----------//
    while(!text.eof())
    {
        text>>a;
        unsigned i=0;
        while(a != arr[i] && i < arr.size())
            i++;
        if(i < arr.size())
        freq[i]++;
        else
        {
            arr.push_back(a);
            freq.push_back(1);
        }
    }}
  • 4
    Debug! Step through your code ... – πάντα ῥεῖ May 17 '16 at 20:17
  • I think you mean to use `if(i < freq.size())` instead of `if(i < arr.size())`. Also see: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – NathanOliver May 17 '16 at 20:20
  • `while(a != arr[i] && i < arr.size()) i++;` -- When `i` is `arr.size() - 1`, another iteration happens. Now `i` is equal to `arr.size()`, so it's pointing past the end of the array. You then use it in `a != arr[i]` -- boom. Switch those conditions in the while loop. – Dan Mašek May 17 '16 at 20:24
  • Hmm, thanks Dan it seems that was the problem, and thanks to the other guys for the suggestions . :) – Mistery Kei May 17 '16 at 20:27

2 Answers2

0

You chould exchange conditions in the while statement

while ( i < arr.size() && a != arr[i] ) i++;

Also this condition is wrong

while(!text.eof())
{
    text>>a;

The eof state can occur after statement

    text>>a;

in the block of the while.

Change it to

while ( text >> a )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Because of this code block you are receiving it. since in the very beginning itself the size of freq array is 1 so its higher index is 0 , but when you are accessing the data in freq by subscript index i, which has become i++ i.e 1 will always try to access freq[1] which never exists.

if(i < arr.size())
        freq[i]++;
Lucky Sharma
  • 173
  • 6