table with names from user - segmentation fault

Hello,
Could you please help me with this simple program? It ends after entering the last name to the table, and I don't know why.
I know the answer is short and simple, please point me the bug and tell me how it should be...

I want the program to simply remember five names and then print them.


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
#include <iostream>
#include <string>
#define N 5
using namespace std;
int main()
{
    string names[N];
    int n;
    string name;

//entering names
    for (n=1; n<=N; n++)
    {
        cout<<"name   "<<n<<"  ";
        getline(cin,names[n]);
        //cin>>names[n];
        //names[n]=name;
    }
    cout<<endl<<endl;
// prints
    for (n=1; n<=N; n++)
    {
        cout<<names[n]<<" . ";
    }
    return 0;
}

Last edited on
Your for loop conditions are wrong. Arrays with size N have range 0 to N-1, not range 1 to N.

Because of this, you are skipping the first element and also writing out of bounds which is causing undefined behavior. You are corrupting the state of your program and causing a segfault most likely.
Last edited on
I didn't think the answer will be SO easy...
Thank you:)
Topic archived. No new replies allowed.