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

C
1

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(
    "nEnter amount of adult tickets:" , 
    "nPlease enter a positive number!");
if (TktAdult < 0) Handle_End_of_File();
else Success(TktAdult);
Posted by: Guest on February-04-2022
0

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i=0, isFloat=0, isChar=0;
    int intNum=0;
    float floatNum=0;
    char str[100];
    printf("Enter a number:");
    scanf("%s",str); // no &
    for(i=0; i<strlen(str); ++i)
    {
        // if not 0-9
        if(!((str[i]>='0')&&(str[i]<='9')))
        {
            if(str[i]=='.')
            {
                isFloat ++;
            }
            else{
                isChar ++;
            }
        }
    }
     if(isChar || isFloat > 1)
     {
         printf("This is not a number.");
     }
     else if(isFloat == 1)
     {
         printf("This is a float.");
         floatNum=atof(str);
         printf("input as float %.2fn",floatNum);
     }
     else {
         printf("This is a valid int.n");
         intNum=atoi(str);
         printf("input as int %dn",intNum);
     }
    return 0;
}
Posted by: Guest on February-04-2022
0

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

#include <stdio.h>
int main()
{
    int num=1;
    int numberRead = 0;
    do{
        printf("Enter a number: ");
        numberRead = scanf("%d",&num);
        while(numberRead != 1){
            printf("That is not a number.n");
           scanf("%*[^n]");  //or fflush(stdin);
            printf("Enter a number: ");
            numberRead = scanf("%d",&num);
        }
        printf("You entered %dn",num);
    }while(num != 0);

    return 0;
}
Posted by: Guest on February-04-2022

Code answers related to "C"

Browse Popular Code Answers by Language