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

一个int型变量接收从键盘读入的值,想在输入为字母时重新输入,应该怎么做呢?

wengbin 发布于 2016-02-29 16:26, 4119 次点击
程序代码:
int GetRequirementFromKeyboard(void)
{
    int Requirement_Number=0;
    int flag=1;
    cout<<"enter a requiremnet-number:";
    cin>>Requirement_Number;
    while(flag)
    {
        
        if(Requirement_Number>0&&Requirement_Number<7)flag=0;//一次正确输入就跳出循环
        else
        {
            cin.clear();
            cout<<"\nOut of rang,please enter a new requiemnet-number\n";
            cin>>Requirement_Number;
        }
                //输入为字母时死循环了,请问是怎么回事?
    }
    return Requirement_Number;
}


[此贴子已经被作者于2016-2-29 16:35编辑过]

7 回复
#2
hjx11202016-02-29 16:31
用cctype头文件中的isapha()函数判断是否是字符
#3
wengbin2016-02-29 16:34
回复 2楼 hjx1120
那样的话,就只能用char型变量来存数字了是吧,我是想试试就用int型能不能行....
#4
wengbin2016-02-29 16:37
回复 2楼 hjx1120
请问如果用char型变量存数字,怎么判断数字是在1-6之间呢?
#5
hjx11202016-02-29 16:54
回复 4楼 wengbin
C语言中int 和char是一样的,C++不知道
#6
hjx11202016-02-29 16:59
回复 4楼 wengbin
字符可以用
.........
char xxxx;
.........
while (xxxx >= '1' && xxxx <= '6')
{
    ........
}
......
#7
rjsp2016-03-01 08:36
程序代码:
#include <iostream>
#include <limits>
using namespace std;

int GetRequirementFromKeyboard(void)
{
    int value = 0;
    for( ; cout<<"enter an number(1-6):", cin>>value, !cin||value<1||value>6; )
    {
        if( !cin )
            cin.clear();
        cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    }
    return value;
}

int main( void )
{
    int n = GetRequirementFromKeyboard();
    cout << n << endl;

    return 0;
}
#8
wengbin2016-03-01 10:08
回复 7楼 rjsp
正是我想要的,谢谢R版
1