Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Input validation check for one integer

Status
Not open for further replies.

aznluvsmc

MIS
Mar 21, 2004
476
0
0
CA
I'd like to do a simple input validation check to see if the user entered ONLY one integer.

The code I current have is as follows

Code:
#include <stdio.h>

int main(void)
  {
  int array[10] = {0};
  int i, rv;
  char c1;

  for(i = 0; i < 10; i++)
    {
    printf("Enter an integer: ");
    while(scanf("%d%c", &array[i], &c1) != 2 || !isspace(c1))
      {
      printf("Please enter only one integer: ");
      while(getchar() != '\n');
      }
    }   

  for(i = 0; i < 10; i++)
    printf("%d ", array[i]);
   
  printf("\n");
  return 0;
}

The program should allow any leading white spaces before the number and any trailing white spaces after the number.

However it should not allow an integer followed by white space followed by another integer which it currently does.

Any help would be appreciated.
 
I had this lying around from some tinkering the other day...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>

int main()
{
   int value;
   for ( ;; )
   {
      char line[sizeof(value) * (CHAR_BIT * 12655UL) / 42039 + 3];
      fputs("Input an integer: ", stdout);
      fflush(stdout);
      if ( fgets(line, sizeof line, stdin) != NULL )
      {
         if ( !isspace(*line) )
         {
            char *end;
            value = strtol(line, &end, 10);
            if ( *end == '\n' || *end == '\0' )
            {
               break;
            }
         }
      }
      puts("ERROR: Try again.");
   }
   printf("value = %d\n", value);
   return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top