0

I am trying to get a integer value from argv[1].

I want to know what happens if the user inputs a character so that I can avoid it. I tried '\0' and currently this doesn't work.

int main(int argc, char* argv[]){
    int MAX_SIZE;
    MAX_SIZE=atoi(argv[1]);
while(MAX_SIZE=='\0'){
    printf("plz input in correct format: ");
    scanf("%d", &MAX_SIZE);}

Any help would be appreciated.

grizzthedj
  • 7,131
  • 16
  • 42
  • 62
  • I think you probably should research and understand how arguments are processed on the command line. I looks to me that you probably should be using argc to know how many elements are in the argv array. It also appears that you probably want to iterate over the argv array given your while loop. – dernst Mar 05 '18 at 15:00
  • Refer this -> https://stackoverflow.com/questions/29248585/c-checking-command-line-argument-is-integer-or-not – Shihab Pullissery Mar 05 '18 at 15:35
  • [don't use `atoi`](https://stackoverflow.com/q/17710018/995714) – phuclv Mar 05 '18 at 17:05

2 Answers2

0

Your code is a bit weird but from what I understand you want to check if a character is a number or not, for that you can use the function isdigit() to check if the entered value is a number or not, something like this:

char c='a';
if(isdigit(c))    //if true, i.e. it returns non-zero value
    cout<<"number";
else             // if false, i.e. it returns zero
    cout<<"Char";

I have written C++ code as I am more comfortable in C++ but the function isdigit() works in both C and C++.

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
  • The question is tagged C, and please note that `isdigit` takes an `int` argument, not `char`. Also *"the behavior of isdigit is undefined if c is not EOF or in the range 0 through 0xFF, inclusive."*. Note too that `'a'` is of type `int` which can be seen from writing `printf("%zu\n", sizeof 'a');` which outputs `4` on my system. – Weather Vane Mar 05 '18 at 16:29
0
# include <stdio.h>
# include <stdlib.h>

int main ( int argc, char *argv[] )
{
   int i, n, a;

   printf("\n   argv[0] = %s\n", argv[0] );
   if ( argc <= 1 )
   {
      printf("\n");
      printf("   argc = %d, no arguments given on command line\n", argc );
      printf("\n");
   }

   for ( i = 1; i < argc; i++ )
   {
      n = sscanf( argv[i], "%d", &a );
      if ( n == 1 )
      {
         printf("   read %d off command line in argv[%d]\n", a, i );
      }
      else
      {
         printf("   sscanf failed, n = %d, argv[%d] = %s\n", n, i, argv[i] );
      }
   }

   return 0;
}
ron
  • 967
  • 6
  • 23