strings into an array, then display them in reverse order

i completed the code but i cant find where the white space is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string name_first[12];
string index_n;

cout<<"Reading in: "<<endl;
for( int index_n=0; index_n<12; index_n++)
{
getline(cin,name_first[index_n]);
cout<<"    "<<name_first[index_n]<<endl;
}

cout<<"Reversed: "<<endl;
for(int index_n = 12; index_n>=0; index_n--)
{
   getline(cin,name_first[index_n]);
cout<<"    "<<name_first[index_n]<<endl;
}
return 0;
}

it shows like this:
Reading in:
Adam
Betty
Charles
Debbie
Elaine
Frank
George
Harry
Igor
Jerry
Karen
Larry

Reversed:

Larry
Karen
Jerry
Igor
Harry
George
Frank
Elaine
Debbie
Charles
Betty
Adam

but it needs to look like this
Reading in:
Adam
Betty
Charles
Debbie
Elaine
Frank
George
Harry
Igor
Jerry
Karen
Larry
Reversed:
Larry
Karen
Jerry
Igor
Harry
George
Frank
Elaine
Debbie
Charles
Betty
Adam
Last edited on
There are at least two problems here. First, too many getlines. Second, the reverse loop starts from an index position outside the array - very dangerous.

I assume you have an input file which contains exactly 12 names.

The first loop reads those names and stores them in the array. It also prints out the string just after it has been read.

Then the second loop (starting from index 12, which is the 13th element of the array - an out of bounds error) attempts to read a further 13 names from the input - this means you'd need to supply at least 25 names via the standard input.

I'd separate the reading from the displaying. Also, start the last loop from index 11, not 12:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    cout << "Reading in: " << endl;
    
    for (int index_n=0; index_n<12; index_n++)
    {
        getline(cin,name_first[index_n]);
    }

    cout << "Original: " << endl;
    
    for (int index_n = 0; index_n<12; index_n++)
    {
       cout << "    " << name_first[index_n] << endl;
    }  
    
    cout << "Reversed: " << endl;
    
    for (int index_n = 12-1; index_n>=0; index_n--)
    {
       cout << "    " << name_first[index_n] << endl;
    }
Last edited on
hi Chervil! thank you very much :) now i know that getline can get me in trouble and i make a lot of sense. thank you very much for sharing your knowledge :) :)
Topic archived. No new replies allowed.