问题
Possible Duplicate:
Need help with getline()
getline not asking for input?
I am working on the following code:
int main()
{
int num;
string str;
cin>>num;
int points[num][2];
for(int i=0;i<num;i++)
{
cout<<"\nPoint"<<i<<":";
getline (cin,str);
points[i][0]=atoi(&str[0]);
points[i][1]=atoi(&str[2]);
}
for(int i=0;i<num;i++)
{
cout<<"\npoint"<<i<<" = "<<points[i][0]<<" "<<points[i][1];
}
The problem with the above code that I am getting is when I enter the num
value as some integer and then press enter, instead of printing...
"Point 0:"
...and waiting for me to enter it prints "Point 0:" and "Point 1:" and then takes the input for Point 1.
For point 0 it automatically takes input as 0 and 0.
回答1:
Following on from Prince John Wesley's reply, try
cin >> num >> endl;
to flush the stream buffer before using it again.
回答2:
Your program hasn't consumed the newline after:
cin >> num;
The conventional way to do so is this:
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
numeric_limits
is defined in <limits>
.
来源:https://stackoverflow.com/questions/7887314/stdgetline-input-not-working-properly-in-c