Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

how to prevent user from entering char when needing int in c

// return -1 on EOF
int GetPositiveNumber(const char *prompt, const char *reprompt) {
  char buf[100];
  fputs(prompt, stdout);
  fflush(stdout);
  while (fgets(buf, sizeof buf, stdin)) [
    int value;
    if (sscanf(buf, "%d", &value) == 1 && value > 0) {
      return value;
    }
    fputs(reprompt, stdout);
    fflush(stdout);
  }
  return -1;
}

// Usage
int TktAdult = GetPositiveNumber(
    "
Enter amount of adult tickets:" , 
    "
Please enter a positive number!");
if (TktAdult < 0) Handle_End_of_File();
else Success(TktAdult);
 
PREVIOUS NEXT
Tagged: #prevent #user #entering #char #needing #int
ADD COMMENT
Topic
Name
8+4 =