LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1026|回复: 5

看看这个程序为什么在linux和freebsd陷入死循环,在windows(mingw或者vc)与solaris下正

[复制链接]
发表于 2009-8-27 11:35:23 | 显示全部楼层 |阅读模式
程序来自:http://www.d2school.com/bhcpp_book/3_11.php
具体见下面:
问题出在“cin.sync();”吧,谁解释下?


#include <iostream>
#include <string>

using namespace std;

struct Person
{
public:   
    Person()
    {
        cout << "Wa~Wa~" << endl;
        cout << "为这个哇哇哭的人,起个名字吧:";
        getline(cin, name);
    }
   
    virtual ~Person()
    {
        cout << "Wu~Wu~" << endl;
    }
   
    string GetName()
    {
        return name;
    }
   
    virtual void Introduction()
    {
        cout << "Hi, my name is " << name << "." << endl;            
    }
private:   
    std::string name;
};

struct Beauty : public Person
{
    virtual ~Beauty()
    {
        cout << "wu~wu~人生似蚍蜉、似朝露;似秋天的草,似夏日的花……" << endl;
    }
   
    virtual void Introduction()
    {
        cout << "大家好,我是美女: " << GetName() << ",请多多关照!" << endl;
    }
};

int main()
{
    while(true)
    {
        Person *someone;
        
        cout << "请选择(1/2/3):" << endl
            << "1----普通人" << endl
            << "2----美人" << endl
            << "3----退出" << endl;
        
        int sel = 0;
        cin >> sel;

        if (cin.fail())
        {
            cin.clear();
        }
        
        cin.sync();
        
        if (3 == sel)
        {
            break;
        }
        
        if (1 == sel)
        {
            someone = new Person;
        }
        else if (2 == sel)
        {
            someone = new Beauty;
        }
        else //用户输入的,即不是1,也不是2,也不是3...
        {
            cout << "输入有误吧?请重新选择。" << endl;
            continue;
        }
        
        cout << someone->GetName() << "的自我介绍:" << endl;
        someone->Introduction();
        
        delete someone;
    }
   
    return 0;
}
发表于 2009-8-27 12:54:02 | 显示全部楼层
没死循环阿,linux
但是也没等我输入名字
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-8-27 14:02:47 | 显示全部楼层
Post by x11;2020840
没死循环阿,linux
但是也没等我输入名字


你输入个不是数字的试试。
如果输入数字,就是不死循环,但是也不等你输入名字。
输入非数字的就死循环了。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-8-27 16:29:11 | 显示全部楼层
找到原因了,需要绑定输入输出流的,我使用了cin.tie(&cout)在前面就可以了。

但是另外一个原因仍然存在,就是在输入选择1 2 或者 3 后,不能等我输入名字,程序就直接继续运行了。
回复 支持 反对

使用道具 举报

发表于 2009-8-27 16:52:23 | 显示全部楼层
可能是终端编码的问题
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-8-27 23:00:11 | 显示全部楼层
Post by jesonlay;2020916
可能是终端编码的问题


不是吧,我使用同一种gnome-terminal测试的。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表