Hi, I am using Visual Studio 2008 Express Edition, and I wrote my code as follow:
====================================code starts
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string *p;
int n;
cout << "Please input the number of students"<<endl;
cin>>n;
p = new string [n];
cout <<"Please input the name"<<endl;
for (int i=0; i<n;i++)
getline(cin,p[i]);
for (int i=0; i<n;i++)
cout << p[i]<<endl;
return 0;
}
==
=====================================code ends
When execute the code, if I input n=4; I can just type 3 names in.
=============================Execution results
Please input the number of students
4
Please input the name
Cristofor
Ivar
Anna
Cristofor
Ivar
Anna
Press any key to continue...
==================================ends
How ever, if the code is
====================================code starts
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string *p;
int n=4;
p = new string [n];
cout <<"Please input the name"<<endl;
for (int i=0; i<n;i++)
getline(cin,p[i]);
for (int i=0; i<n;i++)
cout << p[i]<<endl;
return 0;
}
=======================================code ends
Then I got the right results:
=============================Execution results
Please input the name
Cristofor
Ivar
Anna
Jenny
Cristofor
Ivar
Anna
Jenny
Press any key to continue...
==================================ends
Could anyone tell me why? Thanks a lot!