my program prompt an integer input but if the user type in a character the program crash!

is there any solution to the problem

MANY THANX

Recommended Answers

All 10 Replies

You're gonna have to give us a bit more than that - how about some source code?

hi,

this sounds like buffer overflow :)

as winbatch said 'give us your source code'.

fgets() to read a line of input.
strtol() to validate, convert and check for numeric overflow.

Both provide some success/fail indication in their status returns.

Absolutely right! Here the source code:

#include <iostream.h>
#include <limits.h>

main()
{
      int n;          /* number of values entered */
      cout << "How many values? (1..10) -> ";
      cin >> n;
      cin.ignore(SHRT_MAX, '\n');

      /* control number of value entered by the user */
      while (n<1||n>10)
      {
             cout << "\nInvalid input. Try again (1..10) -> ";
    cin >> n;
    cin.ignore(SHRT_MAX, '\n');
      }
}

Thus so far I have got the input will be within the range 1 to 10 and if the user will type in any value with a fraction part the program cut it off.

But if the user type in a letter the program crash!!!

If cin fails to read the type it expects, it will enter an error state and won't accept further input. Try this:

while (n<1||n>10)
{
  cout << "\nInvalid input. Try again (1..10) -> ";
  cin.clear();
  cin >> n;
  cin.ignore(SHRT_MAX, '\n');
}

Also, you need to initialize n to something. If the first input fails, n will remain indeterminate, and that could cause a number of problems.

So if let's say I initialize n to 0 or 11. Will that be ok?

As long as it's something outside of your valid range, it doesn't matter what value you choose.

:eek: I didn't work!!!

>I didn't work!!!
Not helpful. Post the code that doesn't work and explain how it doesn't do what you want.

That's what I have done:

#include <iostream.h>
#include <limits.h>

main()
{
	int n; /* number of values entered */

	n=0;
	cout << "How many values? (1..10) -> ";
	cin.clear();
	cin >> n;
	cin.ignore(SHRT_MAX, '\n');

	/* control number of value entered by the user */

	while (n<1||n>10)
	{
  	cout << "\nInvalid input. Try again (1..10) -> ";
	cin.clear();
  	cin >> n;
	cin.ignore(SHRT_MAX, '\n');
}

:rolleyes: I thought I had duplicate cin.clear(); as the program could ever get a valid input and thus it will not execute the while Hope this is more helpful!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.