std::getline input not working properly in C++ [duplicate]

狂风中的少年 提交于 2020-01-05 04:38:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!