Help with a Bug

hey everyone, I'm supposed to make a program that can read up to 1000 lines(and place each line inside an array) and then make it output in reverse order. Now everything was going great till I decided to do some final testing before handing it in. I change the const int to 5 for the sake of testing and once the program reads in the 5th line it crashes. I've tried all the methods of my knowledge to fix it but have had no luck. Can anyone help me out with this, please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
using namespace std;

int linesInArray(string linearray[],int &numLines);
void printArray(string linearray[], int numLines);

const int MAX = 5;

int main ()
{
    string linearray[MAX];
    int numLines;

    linesInArray(linearray,numLines);
    printArray(linearray,numLines);

    return 0;
}

void printArray(string linearray[], int numLines)
{
    for (int i=numLines; i>=0; i--)
        cout<<linearray[i]<<endl;
}

int linesInArray(string linearray[],int &numLines){
    numLines=0;
    bool passedMax=true;
    do
    {
         getline(cin,linearray[numLines],'\n');
         if(numLines<MAX)
         numLines++;
         else
            passedMax=false;

    }while(passedMax && !cin.eof());

    return numLines;
}


it's because you're accessing an index that doesn't exist([5] at line 32). I recommend you to use stl containers, such as vector or list to hold your data.
http://www.cplusplus.com/forum/general/112111/
1
2
3
4
5
void printArray(string linearray[], int numLines)
{
    for (int i=numLines; i>=0; i--)
        cout<<linearray[i]<<endl;
}
`numLines' is 5, out of bounds.
In other words it would be

if( numLines < MAX - 1 )

Also the delimiter is by default '\n' so you don't need to put that here: getline(cin,linearray[numLines],'\n');
Last edited on
ahh thanks so much, guys!! really appreciate it!
Topic archived. No new replies allowed.