-6

My program identifies that a user has entered a letter instead of a number, but it doesn't ask for user input after that. I need to be able to prompt the user to enter another value that is a number and create a loop or something that will check the value every time to make sure it isn't a letter/s.

This is the part of my code that does the check for invalid character:

while (!cin.good())
{
cout << "Error! I only accept numbers! Enter in a number." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max());
}
Mofayew
  • 19
  • 1
  • 4

2 Answers2

0

As simple as this may be... this answered my question: http://www.dreamincode.net/forums/topic/186890-c-excluding-letters-on-user-input/

Mofayew
  • 19
  • 1
  • 4
-1

Just don't do this:

int j;
cin >> j;

Because what will only read numbers and you need to read things other than numbers so you can report an error when they are entered.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • I have to create a variable for kWh. so my variable can't be j it is kWh. – Mofayew Sep 30 '15 at 18:34
  • @Mofayew It's not the name of the variable that's the issue, it's the way you're reading. – David Schwartz Sep 30 '15 at 18:38
  • Please help me better understand then. I am doing "double kWh; cin >> kWh;" – Mofayew Sep 30 '15 at 18:48
  • Just don't do what I did in my second line. Don't try to read integers from `cin` because you need to read things other than integers so that you can report errors. – David Schwartz Sep 30 '15 at 18:49
  • I'm not sure what you mean. If I don't use your second line you are saying don't ask for user input? – Mofayew Sep 30 '15 at 18:56
  • 1
    No, I'm saying "don't try to read integers from cin because you need to read things other than integers so that you can report errors". Ask for user input, but then have code that can read all the kinds of user input you need to accept, which includes things other than integers because you need to read them to determine that they're not integers. – David Schwartz Sep 30 '15 at 18:58
  • To put it another way, you're thinking "only integers are valid for my program, so I'll use code that can only read integers". But that's not true. At the low level of the input routine, integers, characters, and all kinds of other things are valid input, they just cause your program to produce error output at the next level up. So you need input code that can read anything, analyze it, and decide whether to produce an error output or not. So that requires input code that can read more than just integers. So no `cin >> someInteger;`. – David Schwartz Sep 30 '15 at 23:03