验证不正常

时间:2017-11-21 04:53:14

标签: c++

当我输入一个字符作为输入时,它会进入无限循环。我无法正确验证我无法找到问题。 如果您输入2个或更多字符,程序将自行退出。

//The Following Program Converts Decimal into Binary
#include <iostream.h>
#include <ctype.h>
#include <conio.h>
#include <process.h>

#define size 8 //change this to change output from 8bit to more or less.

int main()
{
    int dnum;   //Decimal Number to be converted
    char ch;
    do{
    clrscr();
    int i=0,j, ar[size]={0};     //i and j for loop
     do{
        cout<<"Enter Number to convert to binary of:";
        cin>>dnum;
        if(dnum>=256 || isalpha(dnum))
        {
            cout<<"\nEnter number less than 256 only:";
            cin>>dnum;
        }
        else
        break;
        }while(dnum>256);
    dnum+=256;  //trick

    while(dnum>0)        //Process to divide by 2 and store in array
    {
        ar[i]=dnum%2;
        dnum/=2;
        i++;
    }
    for(j=(i-2); j>=0; j--) //Print array in opposite way
    {       if(j==3)
        cout<<" ";
        cout<<ar[j];
    }
    cout<<"\nWanna Find Again?(y/n)";
    cin>>ch;
    }while(ch=='y'||ch=='Y');
    return 0;
}

The Output Screen

1 个答案:

答案 0 :(得分:3)

由于dnum是一个整数,cin如果遇到任何不是整数的内容(例如aaa),将拒绝阅读。您可以检查cin是否失败:

cin >> dnum;
while (cin.fail() || cin.eof()) {
    if (cin.eof()){
        // No more input available. Exit as exception.
        exit(1);
    }
    cin.clear();
    cin.ignore();
    // Print a prompt that the input was wrong.
    cin >> dnum;
}

这样您就可以保证读取有效数字。