Stack overflow. Core dump

#include <iostream>
#include <cstdlib>
#include <stdio.h>

using namespace std;

int main()
{
int i, score[5]={0,0,0,0,0}';
string name[5]={"","","","",""};

string tname="";

i = 1;
for (i=1 ; i<= size; i++)
{
cout << "\n Enter the student name : ";
// cin.ignore(80,'n');

// std::getline(std::cin, name[i]);
cin >> tname;


name[i]=tname;
cout << " \n You type... " << name[i] ;
cin.clear();
i = i + 1;
}
return 0;
}

When I use std::getline, I got error "Segmentation fault. Core dumped" then the program stopped.

I use cin.clear() but does not work.

Book says cin.getline(name,size). But it does not work.

I declare string tname and input into tname and copy into name[i]. But I got the same segmentation error occurred.

Pls advise me if you can. I search several places for input reading command but still got error.

Thank you
The value of variable size is unknown because you did not initialize it. Also take into account that indexes of an array start from 0 not from 1.
Thank you Vlad. I am new to C++ and a student. I define variable size to name[5]. Is it incorrect? What should I change? Pls let me know.

Thks
You can do it the following way

1
2
3
4
5
6
7
#include <string>
...
...
const int size = 5;
int i; 
int score[size]={};
std::string name[size] = {};
Last edited on
Thks. I did as ur advise... but still got the same error. Thks
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 <cstdlib>
//#include <stdio.h>
#include <string>

using namespace std;

int main()
{
    const int SIZE = 5 ;
    int score[SIZE] = {0} ;
    std::string name[SIZE] ;

    //for(i=1 ; i<= size; i++) // *** this is wrong
    // the first element of the array is at position 0
    // and the last at element is at position (SIZE-1)
    // so we iterator over positions from 0 up to (but not incluyding) SIZE
    for( int i = 0 ; i < SIZE ; ++i )
    {
        std::cout << "\n Enter the student name : ";
        std::getline( std::cin, name[i] ) ;

        std::cout << "\n Enter the student score : ";
        std::cin >> score[i] ;

        std::cin.ignore( 80, '\n' ) ; // empty the input buffer
    }
}
Thank you JLBorges. I got it. My program work well. Thank you for pointing me about starting value. Its great!

Thank you everybody who ever help me solve my problem.
Topic archived. No new replies allowed.