Jump to content

Re: check if input is int float or char

- - - - -

  • Please log in to reply
1 reply to this topic

#1
ApprentiC

ApprentiC

    Newbie

  • Members
  • Pip
  • 1 posts
Hello everyone,
I was trying to figure out how to check if input given by the user is an integer. I tried for a while and failed, until today my teacher showed me a cool trick. In c, you can get a return value from the scanf function like this(returns a 0 if it's false, and a 1 if it's true) hope this helps someone!!:

#include <stdio.h>

int main(void)
{
int inputStatus;
char input;

printf("Please enter an integer\n");
inputStatus = scanf("%d",&input);
printf("%d\n",inputStatus);
system("pause");

}

Edited by ApprentiC, 10 February 2011 - 06:59 PM.


#2
jcampos8782

jcampos8782

    Learning Programmer

  • Members
  • PipPipPip
  • 49 posts
Or without a library function:


/* 

	Jason Campos

	Discerns int, float, and char data given as command line args

*/


#include <stdio.h>


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

{

	int isInt = 1;

	int isFloat = 0;

	int isChar = 0;

	char* dataType = "";


	/* Step through command line args one character at a time*/

	char* currChar;

	int i = 0;

	for (i = 1; i < argc; i++)

	{

		currChar = argv[i];

                isInt = 1;

		while (*currChar != '\0')

		{

			if(*currChar < '0' || *currChar > '9')

			{

				if(*currChar == '.' && isInt == 1)

				{

					isInt = 0;

					isFloat = 1;

				}

				else

				{

					isInt = 0;

					isChar = 1;

				}

			}

			currChar++;

		}


		dataType = (isInt)? "int" : "";

		dataType = (isFloat)? "float" : dataType;

		dataType = (isChar)? "char" : dataType; 


		printf("argv[%d] is a %s.\n", i, dataType);


	}


}


Output:
C:\Users\Jason\Desktop\CS47\ifc\ifc>ifc 12 12.5 12.s

argv[1] is a int.

argv[2] is a float.

argv[3] is a char.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users