-2

how can i validate that the number which i scan is in integer in C? i wrote a code that works in every case other than when you enter a float/double like 5.00/6.00 or 13.00 . and almost every other answer i found ignores this situation. my solution so far was:

double tempValue;
printf("enter an integer:");
scanf("%lf",&tempValue);
int value= tempValue;
if(value==tempValue)
   printf("this is an int")
else printf("this isn't an integer");

thanks for reading. better focus on helping instead of down voting. (:

iSkullmao
  • 29
  • 4

5 Answers5

1

scan it into a double, then cast to int and check if there was a truncation:

double x = <your number>;
int y = (int) x;

if (x-y)
{
    // your number is NOT an integer
}
else
{
   // your number is an integer
}
nivpeled
  • 1,810
  • 5
  • 17
  • 4
    @nivpeled It would be even more better if you've provided some explanation with your answer. – AL-zami Nov 24 '19 at 10:12
  • 1
    at first it thought it worked but guess it didn't. still facing the same problem. suppose x= 5.00; the output is that x is an integer. – iSkullmao Nov 24 '19 at 10:26
  • but 5.00 is an integer – nivpeled Nov 24 '19 at 10:42
  • It can be represented with an integer, but it has decimal places so I guess the OP considers it has a float. In C, 5.00 is double literal (while 5.00f is a float and 5 is an integer). – Bktero Nov 24 '19 at 11:05
  • 2
    Arguing about whether 5.00 is an integer is pointless. The question explicitly complained the current code failed to reject “5.00”. So we know that OP wants to reject numerals with a decimal point, in spite of their terminology. They made an error in the question asking for an “integer” rather than describing the character patterns they want to accept or reject. So the problem is not to distinguish numerals that do or do not represent integers but to distinguish numerals that do not contain a decimal point. Arguing about what numbers are mathematically integers is irrelevant. – Eric Postpischil Nov 24 '19 at 11:26
0

In order to discriminate 5.00 and 5, you need to process the string.
Converting to a double with scanf loose this information.

For instance :

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

int main(void) {
        char  buffer[256];
        printf("enter an integer:");
        scanf("%255s",buffer);

        char  valueStr[256];
        sprintf(valueStr,"%d", atoi(buffer));
        if(strcmp(valueStr,buffer)==0)
                printf("'%s' is an integer\n",buffer);
        else
                printf("'%s' isn't an integer\n", buffer);

        return 0;
}

Live Test

This read the input as a string, convert it to an int, convert the int to a string and compare the input string with it.

mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • atoi() should not be use, especially if conversion may fail! Use strtol() instead – Bktero Nov 24 '19 at 11:03
  • @Bktero if the conversion fails `valueStr` will be `0` that is different from the converted string, then it should be ok ? – mpromonet Nov 24 '19 at 11:06
  • Refering to man page: https://linux.die.net/man/3/atoi : "The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as strtol(nptr, NULL, 10); except that **atoi() does not detect errors**." With strtol() you don't have to sprintf() and then strcmp() the strings. See my answer for an example :) – Bktero Nov 24 '19 at 11:07
  • @Bktero: you are right, but in case of atoi error conversion input is not an integer. – mpromonet Dec 21 '19 at 18:06
  • remember that human beings are great to enter anything and everything, even letters when you ask for numbers ;-) – Bktero Dec 31 '19 at 08:11
  • @Bktero: do you have a exemple that make fails the [ideone code](https://ideone.com/ryRaWa) ? – mpromonet Jan 03 '20 at 18:22
  • Oh OK we're not talking about the same thing :) I was talking about atoi() alone. Furthermore, I will tend to believe that `strtol()` costs less than `scanf()` + `atoi()` + `sprintf()` + `strcmp()`. Note that your code can't handle tricky cases like when user inputs "1 c". – Bktero Jan 06 '20 at 07:42
-1
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i, n, ch, done;

    n = scanf("%d", &i);
    if (n == 1) {
        ch = getchar();
        done = ch != '.';
        ungetc(ch, stdin);
    } else {
        done = 0;
    }
    if (done) {
        puts("this is an int");
    } else {
        puts("this is not an int");
    }
    return 0;
}
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
-1

scanf() is made for formatted inputs (this is why it has an f in its name ^^). Here, your inputs are not formatted so you have to do something else.

The best way is to get the user input with fgets() and then to check the content. As mention is a previous comment, strtol() is the dedicated function for this task: you try to convert the string to a number and see if the conversion succeeds... or not.

Here is an example:

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

#define SIZE    1024

void convert() {

    // Get user input
    char buffer[SIZE] = {0};
    printf("Enter number: ");
    char* result = fgets(buffer, SIZE, stdin);
    assert(result != NULL);

    printf("User input = %s\n", buffer);    

    // Convert
    char* end = NULL;
    long int value = strtol(buffer, &end, 10);

    if (buffer[0] == '\n') {
        // The user didn't input anything
        // and just hit 'enter' kit
        puts("Nothing to convert");
    }    
    else if(*end == '\n') {
        // Assuming that 'buffer' was big enough to get all characters,
        // then the last character in 'buffer' is '\n'.
        // Because we want all characters except '\n' to be converted
        // we have to check that 'strtol()' has reached this character.
        printf("Conversion with success: %ld\n", value);
    } else {
        printf("Conversion failed. First invalid character: %c\n", *end);
    }
}

int main() {
  while(1) convert();
}

If you really want an int and not a long int, then you have to trick a little. My first idea would be to do something like this:

// Fits in integer?
int valueInt = value;
// some bits will be lost if 'value' doesn't fit in an integer
// hence the value will be lost

if (valueInt == value) {
  printf("Great: %ld == %d\n", value, valueInt);
} else {
  printf("Sorry: %ld != %d\n", value, valueInt);
}
Bktero
  • 722
  • 5
  • 15
-1

Considering that you will never be certain that a arbitrary number is an integer (unless you check the input and treat it as a string).

The best approximation would be to check that the value compare to supposed the integer value would be lower than the machine epsilon

bool doubleMaybeInteger(double input) {
    return ((input - floor(input)) < DBL_EPSILON)
}

dvhh
  • 4,724
  • 27
  • 33