注册 登录
编程论坛 C++教室

cin getline输入问题

kspliusa 发布于 2009-09-27 16:12, 1360 次点击
大家好,我想问一个问题。就是
#include <iostream>
#include <cstring>

using namespace std;

struct datas{
    string name;
    double diameter;
    double weight;
};

int main()
{
    datas *pn = new datas;

    cout<<"Enter the diameter of the pizza:\n";
    cin>>pn->diameter;
   
    cout <<"Enter the name:\n";
    getline(cin,pn->name);

    cout <<"Enter the weight of the pizza:\n";
    cin>>pn->weight;

    cout <<pn->name<<"\n"<<pn->diameter<<"\n"<<pn->weight<<endl;
    delete pn;
    return 0;
}
这个程序为什么不能在输入diameter后不等待输入name而直接就出现Enter the name:Enter the weight of the pizza麻烦哪位高手帮帮我!!先谢谢了!
4 回复
#2
pywepe2009-09-27 17:39
回复 楼主 kspliusa
  get与getline区别不是很大,但一个明显的区别是get遇到'\n'字符后便返回,这是'\n'还在缓冲区中,所以下次读出来的将是'\n',而getline遇到'\n'也返回,但它会把'\n'从缓冲区里移除掉  
  所以很多时候用getline方便些   
#3
kspliusa2009-09-27 18:16
回复 2楼 pywepe
谢谢啊!!可是为什么我上面的程序输入的时候出了问题啊,帮我看看吧!!
#4
gz812009-09-27 19:22
在getline(cin,pn->name);前面加一句cin.ignore();即可。

不要问我为什么,我觉得google或baidu会比我说得更清楚。:)

[ 本帖最后由 gz81 于 2009-9-27 19:59 编辑 ]
#5
kspliusa2009-09-28 15:35
回复 4楼 gz81
呵呵,好的,不过还是非常感谢指教!!
1