4

I have a signed integer variable when I do this in main, it is giving me "Error" for integer values as well.

int main(){
    unsigned int a;
    while(cin>>a){
        if(!isdigit(a)){
            cout<<"Error"<<endl;
        }
    }
}

[EDIT]: Thanks to all the responses, I understood the issue. Now, how do I check if cin is reading integer only and not alphabets or any other character. Is there any function for that in c++. Thanks

user1035927
  • 1,653
  • 5
  • 17
  • 18
  • Probably because your character is being sign-extended. Please see http://stackoverflow.com/questions/8083083/how-do-you-cope-with-signed-char-int-issues-with-standard-library – Mordachai Nov 19 '11 at 23:49

3 Answers3

4

The problem is that isdigit() takes a character, not an integer.

It returns true when the character is '0', '1', etc... Which has ascii values of 48, 49, etc...

Try it this way instead:

char a;
while(cin>>a){
    if(!isdigit(a)){
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • *"Which has ascii values of 48, 49, etc..."* -- unless the character set is something stupid like ebcdic. Admittedly, I've never seen such an implementation. – Benjamin Lindley Nov 19 '11 at 23:54
  • I've seen an implementation that actually had EBCDIC parsing: Perl's CGI.pm. Granted, it's not C++, but still, ... – moshbear Nov 20 '11 at 00:01
  • @BenjaminLindley: Well, even if the user's execution CS is EBCDIC, the ASCII value of `'0'` is still 48... – Kerrek SB Nov 20 '11 at 00:35
1

Try this :

std::cout << "Is digit : " << isdigit('9');

Then read this :

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

And if you still have trouble let us know.

FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • Thanks for the link...so, how do I check if cin is reading only integers and not alphabets or anything else? – user1035927 Nov 19 '11 at 23:53
  • 1
    @user1035927 If you read the link and the example you will understand. I preferred this way rather than giving you the solution directly. The input to the function must be the ASCII value of a digit. Check Mysticial's answer for more details on that. – FailedDev Nov 19 '11 at 23:56
1

If you want to be sure that you successfully read the type you wanted you can use istream::good()

unsigned int a;
std::cin >> a;
if(!std::cin.good()) {
    std::cout << "Error!\n";
} else {
    std::cout << a;
}
bames53
  • 86,085
  • 15
  • 179
  • 244
  • Hi Bames, can this same thing be done in a while loop?, because I have to continuously read input from a text file. Thanks – user1035927 Nov 21 '11 at 00:32
  • Yes, you can use it in a loop. If there is an error with the user's input but you want to clean up and continue reading input you can clear the error on the stream with the clear() member function. – bames53 Nov 21 '11 at 09:24