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

为什么会进入死循环,怎样修改才正确

墨香555 发布于 2011-09-20 17:05, 608 次点击
int setgolf(golf & g)
{
    int next;
    std::cout << "Please enter golfer's full name: ";
    std::cin.getline(g.fullname, Len);
    if (g.fullname[0] == '\0')
        return 0;                // premature termination
    std::cout << "Please enter handicap for " << g.fullname << ": ";
    while(!(std::cin >> g.handicap))
    {
        std::cin.clear();
        std::cout<<"please enter a integer: ";
    }
    while (std::cin.get() != '\n')
        continue;
    return 1;
}
Enter up to 5 golf team members:
Please enter golfer's full name: reg
Please enter handicap for reg: w(输入w后就进入死循环)
2 回复
#2
nicum2011-09-20 18:27
程序代码:

int setgolf(golf & g)
{
    int next;
    std::cout << "Please enter golfer's full name: ";
    std::cin.getline(g.fullname, Len);
    if (g.fullname[0] == '\0')
        return 0;                // premature termination
    std::cout << "Please enter handicap for " << g.fullname << ": ";
    while(!(std::cin >> g.handicap))              //当输入w的时候,cin>>g.handicap返回真,退出while循环
    {
        std::cin.clear();
        std::cout<<"please enter a integer: ";
    }
    while (std::cin.get() != '\n')              //如果w输完按了回车,while循环也立即退出
        continue;
    return 1;
}
Enter up to 5 golf team members:
Please enter golfer's full name: reg
Please enter handicap for reg: w(输入w后就进入死循环)


[ 本帖最后由 nicum 于 2011-9-20 18:39 编辑 ]
#3
墨香5552011-09-21 14:48
我知道啦 在while循环里加一个std::cin.get(next);就不会进入死循环啦
1