user1751615
user1751615

Reputation: 33

Why is this Vector subscript out of range?

Yes I am learning vectors currently. I am trying to read in a text file, count the number of unique words, and then output a text file(will do later). Could use some assistance in grasping what is going on and why/how to fix?

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include<vector>
using namespace std;
string toLower(string str);
string eraseNonAlpha(string Ast);
string  wordWasher(string str);
int countUniqenum(vector<string>&v);
int main()
{   
    ifstream inputStream; //the input file stream
    string word; //a word read in from the file
    string words=wordWasher(word);
    inputStream.open("alpha.txt");
    if (inputStream.fail())
    {
        cout<<"Can't find or open file"<<endl;
        cout<<"UR a loser"<<endl;
        system("pause");
        return 0;
    }//end if

    while (!inputStream.eof())
    {
        inputStream>>words;

    }//end loop

    vector<string> v;
    v.push_back(words);
    int unique =countUniqenum(v);
    cout<<unique<<endl;
    inputStream.close();

system("pause");
return 0;

}

string toLower(string str)
{

       for(int i=0;i<str.length();i++)
       {
               if (str[i]>='A'&& str[i]<='Z')
                 str[i]=str[i]+32;
       }
     return str;
}
string eraseNonAlpha(string str)
{
    for(int i=0;i<str.length();i++)
    {
        if(!((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))) 
        {str.erase(i,1);
        i--;
    }   
    }
    return str;
}

string  wordWasher(string str)
{   str=eraseNonAlpha(str);
    str=toLower(str);
    return str;
}                               
int countUniqenum(vector<string>&v)
{ int count=0;
  for(int i=0;i<v.size();i++)
  {
          if(v[i]!=v[i+1])
          count++;
  }     
  return count;
}  

Upvotes: 0

Views: 163

Answers (3)

sethi
sethi

Reputation: 1889

Shouldn't you vector be sorted for this to work..you are just checking the adjacent words are same or not

if(v[i]!=v[i+1])

Upvotes: 0

abjuk
abjuk

Reputation: 3772

It's the line if(v[i]!=v[i+1]). On your last trip through the loop, v[i] is the last element of the vector and v[i+1] is off the end.

A simple fix is to change the loop to for(int i = 0; i < v.size() - 1; i++). I'm not sure that function really does what you want it to do, but that'll at leaset get rid of the crash.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227468

You are definitely going beyond bounds here:

for(int i=0;i<v.size();i++)
{
      if(v[i]!=v[i+1])
//               ^^^

There may well be other errors.

Upvotes: 2

Related Questions