Lloyd
Lloyd

Reputation: 85

How can I exclude floating point numbers from getting the input and send error message to the user?

I need to code a program that only accepts integer from 1-10(excluding characters and floating point numbers). I am using fgets. It runs but I cannot exclude floating point numbers. This is part of my code:

char choice[256];
int  choice1;

fgets(choice, 256, stdin);
choice1 = atoi(choice);
if (choice1 > 0 && choice1 <= 10)
{
    switch (choice1)
    {
    case 1:

    ...

    case 10:

Help?

Upvotes: 3

Views: 305

Answers (3)

phoxis
phoxis

Reputation: 61910

EDIT

Something like below may help. You need to change as per your requirement. See the manpage of strtol

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

int main (void)
{
  int choice1;
  char *endptr, choice[256];

  fgets (choice, 256, stdin);

  choice1 = strtol (choice, &endptr, 10);
  if (endptr != NULL && *endptr != '\n')
  {
    printf ("INVALID\n");
  }

  printf ("%d\n", choice1);
  return 0;
}

The endptr will hold the location of the location of the first invalid character. Comparison with \n is required because the fgets will also store the newline in the buffer. You might want to process this in some other way. The above code shows an outline.

Or you might like to manually iterate on the string and discard it depending on the contents. May be something like below will work.

fgets (choice, 256, stdin);
for (i=0; choice[i] != '\0' || choice[i] != '\n'; i++)
{
  if (!isdigit (choice[i]))
  {
    flag = 0;
    break;
  }
}

When you use fgets if the line is terminated with a newline character, it will be stored in the string.

Upvotes: 1

Tushar Chhabhaiya
Tushar Chhabhaiya

Reputation: 700

You can take help do while loop.

int c;
do
{
 c = getchar();
if(atoi(c) > 0 && atoi(c) <=9)
{
// append character to character array(string)
// For user to under stand what he has entered you can use putchar(c);
}
}while(c!=13)

This is not exact solution but you can do something like this. unfortunately I don't have installed c compiler on my machine so I have not tasted this code.

Upvotes: 0

unwind
unwind

Reputation: 399843

You can use strtol() to do the conversion instead of atoi(). This will give you a pointer to the first character that wasn't part of the number. If that character isn't a blank, the number wasn't integer.

Upvotes: 5

Related Questions