Question:
C programming question... how to check if variable does not equal int?
Alex
2012-10-11 15:00:48 UTC
Hi,
i have a variable which is an input variable and i need to check if the variable is an int

my code i currently have is

if (quantity != type(int))

^ this line isnt a correct line

how can i write an if statement that checks if the variable is a certain type, such as a float or int type


Thanks!
Eight answers:
Jonathan
2012-10-11 17:29:33 UTC
After reading all of your other replies, I have a suspicion that none of them picked up on something you didn't say. What is the declared type of the variable "quantity?" I'm wondering now if it is required by your teacher to be double or float.



If quantity is defined one of the following two ways:



        double quantity;

        float quantity;



and if you use an appropriate scanf() call to get the value into it, then the teacher's request for a "defensive" test suddenly makes a lot of sense. The user could type in any value, integer or not, and the variable quantity would hold what the user entered... but not necessarily what you want to accept. It may not be an integer, then.



A way to test this then would be something like this:



        if ( quantity = floor(quantity) )

            { /* it is an integer */ }

        else

            { /* it is not an integer */ }



If I'm wrong about my guess above, then read the other responses and consider them. But I suspect this is the issue you are dealing with.



You will need to include this include statement, though, because floor() is declared there for you:



#include



EDIT: You don't do the test BEFORE the user enters the value. You let the user enter the value FIRST, perhaps using scanf() to do that. THEN you do the test. C does not have a crystal ball that works. You can't control what the user types before they type it. Just let them give you a value first, then do the test I mentioned.
green meklar
2012-10-11 20:01:22 UTC
You don't. The computer in any case does not store that information. During execution, an int is just a sequence of 4 bytes. Its identity as an 'integer' is defined only by how the machine code instructions happen to treat it; and there is absolutely nothing stopping you from interpreting the same section of memory as multiple data types simultaneously.



If you want your inputs to be safe, generally what you do is take it in the form of a string (which in C is a null-terminated char array), and then parse it to get the data you want. So long as the memory block into which you read the string is appropriately large, this is considered a reasonable way to get user input, at least for beginners. It turns out the straightforward technique is not entirely safe, and you have to use more advanced techniques to make it safe, but you probably don't need to worry about that right now.
?
2012-10-11 16:17:48 UTC
I agree with Ratchetr. One thing you can do is read everything in on a string, then use the atoi() function in the stdlib.h library with preprocessing using the ctype.h library. You can make sure each character is a digit, before passing the C-string to atoi(). If my program is really sensitive, I do that, but otherwise the strongly typed ideology behind C helps with that.



You cannot check explicitly if a inputted value is an integer data type, but more or less that the characters can resemble an integer. Maybe this small example helps:



#include

#include

#include

#include



int main(int argc, char *argv[]) {



int true_int=0,conv_int;

int c;

char *str_int;



str_int = (char*)malloc(80*sizeof(char));



// Note you should probably not use scanf anyways

// but just for quick demonstration purposes



printf("Please enter an integer: ");

scanf("%d%*[^\n]%*c",&true_int);



printf("Please enter same integer: ");

scanf("%s",str_int);



printf("%d\n",true_int);

printf("%s\n",str_int);



for (c=0;c
if (!isdigit(str_int[c])){

printf("You didn't enter an integer!\n");

return -2;

}

}



conv_int = atoi(str_int);



if (conv_int != true_int){

printf("Error\n");

return -1;

}

else

printf("%d == %d\n",conv_int,true_int);



return 0;

}



Anyways, just hopefully helpful to you.
Ratchetr
2012-10-11 15:08:39 UTC
You can't, nor do you need to.



C is a strongly typed language, meaning that at the point where you are writing that code, you already know what type quantity is, and it can only be 1 specific type. C doesn't have an object type that can hold more than one other type.



Just curious, what problem are you trying to solve where this would be the solution? There is probably a better way.
Yuko
2012-10-11 16:02:48 UTC
You can use the following:

if (typeid(quantity) != typeid(int))



But here's a note....The only reason I use this is because I have a function that uses templates and at one point I need to check for a certain type. You won't run into this problem if you're just using a normal function definition because your input will be cast into the argument type. For example, if I have the following function:



void myfunction(int x)

{

//some definition

}



but when I call my function I do this......



double input = 4.2;

myfunction(input);



The value of input gets cast to an int (4.2 turns into 4...well...basically anyway...), which can lead to some unexpected results.



I think probably what your teacher expects is for you to check the input in an attempt to take preventative action against runtime errors.

For example. Take the following [unrealistically simple :) ] function:



void myNum(int * pInt)

{

int iNumber = *pInt;

}



This is fine as long as you made sure that pInt actually points to something...As follows....



int * p = (int *)malloc(sizeof(int));

*p = 37;

myNum(p);



But let's say you forgot to say what p was, intending to set it later somewhere else...



int * p = NULL;

//pretend there is other code here where you assume p is going to be made to point to something.

myNum(p);



The compiler won't complain about this. But you'll get an error at runtime because when you dereference the pointer inside myNum() you'll be trying to read a null pointer. You can get around this by adding a check inside your function definition.

void myNum(int * pInt)

{

int iNumber;

if (pInt == NULL)

{

printf("Null pointer!");

return;

}

else

{

iNumber = *pInt;

}

}



Now when you try to feed the function a null pointer, it catches it before it's too late and the function returns before trying to dereference the pointer. Believe me, this sort of check is invaluable and when you have 20,000 lines of code can help you identify a problem WEEKS sooner than a runtime error you get because you forgot to check for invalid input somewhere.
Joaquín
2012-10-11 15:47:33 UTC
You can:



1) Take a char array as input and use atoi() to convert that to an integer. Be careful with this function because if there is no valid conversion, atoi() will return 0.



http://www.codingunit.com/c-reference-stdlib-h-function-atoi-convert-a-string-to-an-integer



2) Take a char array as input and use isdigit() to check whether each element in the array is an integer or not (this function will not take into consideration the minus sign, only numbers in the range [0; 9])



http://www.elook.org/programming/c/isdigit.html



3) Similar to atoi, you can use strtol()



http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/



4) Write your own function to verify whether a given cstring represents an integer or not. You can use the ASCII table to do so.



http://www.asciitable.com/index/asciifull.gif



If you were to do this in C++, you could just do the following. if (std::cin.fail()) { std::cin.clear(); std::cin.ignore() }
2016-03-16 03:39:43 UTC
It's the counter for the loop. Every time the program goes through the loop n will increment by 1. The loop program will continue to loop until n<=10, the it will jump out of the loop. Hope this helps.
?
2016-11-15 10:20:43 UTC
Not Equal In C


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...