0

Here, firstly i am trying to take size of an array as input, and then that number of students as input again. I have used getline(cin, arr[i]) to include white space as input to store both the first name and last name. My codes are shown below. But, it is skipping arr[0] and starting to store the values starting from arr[1]. If I don't use variable lenght array it still skips arr[0]. Please help.

#include <iostream>
#include <string>
using namespace std;
int main()
{
int s;
cout<<"Enter the number of students\n";
cin>>s;
string arr[s];
cout<<"Enter the name of the students\n";
    for (int i=0;i<s;i++){
    getline(cin, arr[i]);
cout<<"The name of the students are:\n";    
    for (int i=0;i<s;i++){
    cout<<i<<"="<<arr[i]<<"\n";

    } 
return 0;
}

OUTPUT:
Enter the number of students
4
Enter the name of the students
John Smith
Alfred Kox
Mike Holfman
The name of the students are:
0=
1=John Smith
2=Alfred Kox
3=Mike Holfman

Why arr[0] is not storing any thing and taking only 3 inputs? I can't figure out, what is wrong in here, please help.

mike_s
  • 35
  • 5
  • 1
    How does this compile? C++ does not support variable-length arrays. – cadaniluk Dec 21 '15 at 14:51
  • @CoryKramer that is the wrong dupe. The issue is with mixing `>>` and `getline`. I am changing the dupe target. – NathanOliver Dec 21 '15 at 14:53
  • @NathanOliver Good catch, that is another big issue with the existing code. I'll leave a link here for the other question so they can fix their array allocation too https://stackoverflow.com/questions/737240/c-c-array-size-at-run-time-w-o-dynamic-allocation-is-allowed – Cory Kramer Dec 21 '15 at 14:54
  • @CoryKramer Okay. I do agree that is another issue but unfortunately there is a very popular compiler out there that allows it as an evil extension. It is about as bad as MSVS non const reference to temporary extension. – NathanOliver Dec 21 '15 at 14:56
  • @cad If i dont use variable lenght array, it still skips, arr[0]. – mike_s Dec 21 '15 at 15:02
  • @NathanOliver could u or someone please reopen this? My purpose is not getting solved. I am new in here. Thank you. – mike_s Dec 21 '15 at 15:08
  • 1
    @mike_s The problem is already answered in the link to question. I suggest you read the answer as it tells you what to do to call `getline` after you use `>>` – NathanOliver Dec 21 '15 at 15:11

0 Answers0