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

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!!!

Edited 3 Years Ago by pyTony: fixed formatting

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.

>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!

This article has been dead for over six months. Start a new discussion instead.