Click to See Complete Forum and Search --> : C++ Beginner - Limiting cin to integer or text only
kuphryn
09-16-2001, 07:33 PM
Hi,
I have new to C++ programming. I would like to know how to define or limit the cin function so that it would only accept integer or text rather than anything.
I like to use the if statement and close the program if the user enters an invalid integer or text. For example:
if (blah != integer)
....blah...;
I have tried replacing "integer" with "int." That does not work. Is there anything I use put inplace of "integer" that would set it to either integer or text only? Thanks.
Kuphryn
brianshields
09-16-2001, 07:57 PM
Hi there,
What you want, in the way you are doing it, is not possible - you basically have to take input as a string and then throw an error back to the user if any of the characters are not numeric.
The basic C++ objects such as istream and ostream (of which cin and cout are derivative) suck. All I can suggest is use someone else's functions that ignore non-numeric keypresses, or write your own routine to capture keyboard input. This is the sort of thing Java has standardised and made work well.
I've never used cin/cout since exercises I had to do for my degree. Standardisation of C++ is basically really badly done.
kuphryn
09-16-2001, 08:11 PM
I think I know what is going on. I can just define the object as a string or an integer. That way, I can use if for other purposes like specific integers.
Kuphryn
dighn
09-17-2001, 11:32 PM
That's funny because I've always thought console IO in java is more of a pain then in C++. And how do you take an input in Java that ignores non-numeric keyppresses? I'm aware of no such thing (but then I never really got into Java)
------------------
Keep it brief
[This message has been edited by dighn (edited September 17, 2001).]
brianshields
09-20-2001, 09:13 PM
Originally posted by dighn:
That's funny because I've always thought console IO in java is more of a pain then in C++. And how do you take an input in Java that ignores non-numeric keyppresses? I'm aware of no such thing (but then I never really got into Java)
Yeh, IO is a little trickier, but there are standardised ways to bypass it. I could give code that would work in C++ but it would be platform specific (DOS, Win32, MFC, as a custom control). In Java I could give _1_ piece of source and say "use (so and so) class to capture the input of each key"
That's what I was getting at
dighn
09-20-2001, 11:23 PM
Originally posted by brianshields:
Yeh, IO is a little trickier, but there are standardised ways to bypass it. I could give code that would work in C++ but it would be platform specific (DOS, Win32, MFC, as a custom control). In Java I could give _1_ piece of source and say "use (so and so) class to capture the input of each key"
That's what I was getting at
Would you mind telling me how? It sounds interesting http://www.sharkyforums.com/ubb/smile.gif
------------------
Keep it brief