only int

Started by
13 comments, last by nobodynews 17 years, 6 months ago
i dont have my book with me! What can i call that makes sure the input is and integer?
Advertisement
could you be more precise about what type of input you are talking about?!
so it accepts only numbers, no letters or other signs.


example
int num;
cout<< "enter number 1-5" << endl;

cin >> num; // before it gets assigned make sure the input is a number.


You would probably have to do non-blocking input so that you can check the pressed key in real-time.
Im positive there is a simple call, i just dont remember it.
Maybe it was part of the Standard Template Library.
Quote:Original post by Dave
You would probably have to do non-blocking input so that you can check the pressed key in real-time.

You'd just have to do the same thing cin already does, just filtered so that letters and such are ignored. That would be really hard, and completely not worth the effort.
cout << "Enter 1-5.  Please do not enter any letters or other signs." << endl;cin >> num;if(!cin) cout << "I said please :(" << endl;

CM
while(isalpha(input)){       cin >> input;}


EDIT:
make sure to include ctype
"Computer games don't affect kids; I mean if Pac-Man affected us as kids, we'd all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music." - Kristian Wilson, Nintendo, Inc, 1989
Quote:Original post by Conner McCloud
Quote:Original post by Dave
You would probably have to do non-blocking input so that you can check the pressed key in real-time.

You'd just have to do the same thing cin already does, just filtered so that letters and such are ignored. That would be really hard, and completely not worth the effort.
cout << "Enter 1-5.  Please do not enter any letters or other signs." << endl;cin >> num;if(!cin) cout << "I said please :(" << endl;

CM


Fair play.

I don't think i have ever tried it in C++ :/
its not working for me?

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
int answer = 0;
while(answer != 8){
cout << "Enter number"<< endl;
cin >> answer;
if(!cin) {
cout << "I said please :(" << endl;
answer = 9;}

cout << "The answer is "<< answer <<endl;
}
return 0;
}
MSDN exemple of cin do just that, but it use cin.fail() instead of !cin..... don't forget to .clear() on error ;)

This topic is closed to new replies.

Advertisement