Quantcast
Channel: CodeGuru Forums - Visual C++ Programming
Viewing all articles
Browse latest Browse all 3029

error : string subscript out of range

$
0
0
Hello guys i have a quick question
I have an assignment where i have to prompt the user to enter the name of a file
then open that file and read names of students and what level they are at university
eg : John Wilkins, sophomore
Dan Robertson, junior
etc..

i did the code and it compiles perfectly, but when i input the name of the file it gives me error: string subscript out of range.
here's the code:

Code:

#include <iostream>
#include <cstring>
#include <string>
#include<ctime>
#include <fstream>
using namespace std;

int *  read_file(string filename)
{
        enum year_classification{ freshman, sophomore, junior, senior, graduate};
        int count[5], i;
        for (int j=freshman; j<=graduate; j++)
                count[j]=0;
        string word;
        ifstream infile;
        infile.open(filename.c_str());
        if ( infile.is_open() )
        {
                while( !infile.eof() )
                {
                        getline(infile,word);
                        i=0;
                        while (word[i] != ',')
                        {
                                i++;
                        }
                        switch ( word[i+2] )
                        {
                                case 'g': count [graduate] ++;
                                                        break;
                                case 'j': count [junior] ++;
                                                        break;
                                case 'f': count [freshman] ++;
                                                        break;
                                case 's': {if( word[i+2] = 'o') count [sophomore]++; else count [senior]++;
                                                        break;}
                        }
                }
        }
        else cout<<"could not open file"<<endl;
        return count;
}




int main()
{
        enum year_classification{ freshman, sophomore, junior, senior, graduate};
        string filename;
        cout<<"Please enter the name of the file : ";
        getline(cin,filename);
        cout<<"Number of graduate : "<<read_file(filename)[graduate]<<endl;
        cout<<"Number of senior  : "<<read_file(filename)[senior]<<endl;
        cout<<"Number of sophomore: "<<read_file(filename)[sophomore]<<endl;
        cout<<"Number of junior  : "<<read_file(filename)[junior]<<endl;
    cout<<"Number of freshman : "<<read_file(filename)[freshman]<<endl;
        return 0;
}


Viewing all articles
Browse latest Browse all 3029

Latest Images

Trending Articles



Latest Images