I am writing a C program and I have to read parameters by command line. How can I check if the argument passed to my program is a string (that is to say an array of characters) or an integer? Is there any immediate call I can use in C?
4 Answers
You can call isdigit() on each character of the string, and if it's true for all characters you have an integer, otherwise it's some alphanumeric string.
You can also call strtol to parse the string as an integer. The second argument returns a pointer to the first non-numeric character in the string. If it points to the first character, it's not an integer. If it points to the end, it's an integer. If it points somewhere in the middle, it's an integer followed by a sequence of non-numeric characters.
Comments
How can I check if the argument passed to my program is a string (that is to say an array of characters) or an integer?
Command line arguments are always passed to a C program as strings. It's up to you to figure out whether an argument represents a number or not.
int is_number(char const* arg)
{
// Add the logic to check whether arg is a number
// The code here can be simple or complex depending on the
// level of checking that is necessary.
// Should we return true or false if the argument is "1abc"?
// This is a very simple test.
int n;
return (sscanf(arg, "%d", &n) == 1);
}
int main(int argc, char** argv) // argv is array of strings.
{
int i = 0;
for ( i = 1; i < argc; ++i )
{
if ( is_number(argv[i]) )
{
// Use the argument.
}
}
}
Comments
You can try to check whether all string characters fall in the range of numbers from 0-9.check this program for instance :
#include <stdio.h>
int checkString(char *Str)
{
char *ptr = Str;
while( *ptr )
{
// check if string characters are within the range of numbers
if( ! (*ptr >= 0x30 && *ptr <= 0x39 ) )
{
return 0;
}
ptr++;
}
return 1;
}
int main(int argc,char *argv[])
{
// does argv[1] consist entirely of numbers ?
if( checkString(argv[1]) )
{
/* if it does , do something */
puts("success");
}
else
{
/* do something else */
}
return 0;
}