Check to make sure argv [1] is a C ++ integer

For my program, I have to make sure that the user enters only a positive INTEGER. for example, if the user entered 12hi, he should not run the program and print on the std error. I'm not quite sure how to implement this.

int main(int argc, char *argv[])   
{ 
    if(atoi(argv[1]) < 1)
    {
        cerr << "ERROR!"<< endl;
        return 1;
    }
    return 0;
}
+2
source share
5 answers

Pass it std::istringstreamand make sure that all data is processed:

if (a_argc > 1)
{
    std::istringstream in(a_argv[1]);
    int i;
    if (in >> i && in.eof())
    {
        std::cout << "Valid integer\n";
    }
}

Watch the online demo at http://ideone.com/8bEYJq .

+4
source

Ok, my revised answer. sscanf didn't behave as I thought, and strtol provides the best C-like solution that is very portable.

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

int main(int argc, char* argv[])
{
  for (int i=1; i < argc; i++){
      char* end;
      long val = strtol(argv[i], &end, 10);
      if (argc >= 2 && !end[0] && val >= 0){
          printf("%s is valid\n", argv[i]);
      } else {
          printf("%s is invalid\n", argv[i]);
      }
  }
  return 0;
}

Example output :. /a.out 10 -1 32 1000 f -12347 +4 --10 10rubb

10 is valid
-1 is valid
32 is valid
1000 is valid
f is invalid
-12347 is valid
+4 is invalid
--10 is invalid
10rubbish is invalid

, strtol int. , end [0] , , 10rubbish, , 10. , , , 0 .

atoi() , . 0 .

sscanf() , , 10rubbish, 10.

, op argv [1], , .

+1

, , Standard C,

long strtol (const char* str, char** endptr, int base)

<cstdlib> , - () "-" "+", . , char * endptr '\ 0', , .

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])   
{
    if (argc < 2) {
        return 1;
    }

    char * endp;
    long i = strtol(argv[1],&endp,10);
    if (!*endp) {
        cout << "The value of \"" << argv[1] << "\" is " << i << endl;
        return 0;
    }
    cerr << "\"" << argv[1] << "\" is not an integer" << endl;
    return 1;
}

LATER... :

#include <cstdlib>
#include <iostream>
#include <climits>

using namespace std;

int main(int argc, char *argv[])   
{
    if (argc < 2) {
        return 1;
    }

    char * endp;
    long i = strtol(argv[1],&endp,10);

    if (*endp) {
        cerr << "\"" << argv[1] << "\" is not an integer :(" << endl;
        return 1;
    }
    if (endp == argv[1]) {
        cerr << "Empty string passed :(" << endl;
        return 1;
    }
    if (i < 0) {
        cerr << "Negative " << i << " passed :(" << endl;
        return 1;
    }
    if (i <= INT_MAX) {
        cout << "Non-negative int " << i << " passed :)" << endl;
    } else {
        cout << "Non-negative long " << i << " passed :)" << endl;
    }
    return 0;

}

. - , ULONG_MAX LONG_MAX.

+1

, argv[1] (, ). isdigit().

http://www.cplusplus.com/reference/cctype/isdigit/

OP ( http://codepad.org/SUzcfZYp):

#include <stdio.h>          // printf()
#include <stdlib.h>         // atoi()
#include <ctype.h>          // isdigit()

int main(int argc, char *argv[])   
{ 
    if( argc != 2 ) {
        return 0;
    }

    char * pWord = argv[ 1 ];
    char c = 0;
    for( int i = 0; c = pWord[ i ], c ; ++i ) {
        if( ! isdigit( c ) ) {
            return 0;
        }
    }

    int argvNum = atoi( argv[ 1 ] );
    printf( "argc = %d, argv[ 1 ] = %s, argvNum = %d\n",
        argc, argv[ 1 ], argvNum );
}
0

++, , , , , ?

:

  • /

1.IF/ELSE   #include

int main(int argc, int **argv) {
    if (!isdigit(argv[1])) {
        // handle code if it not a digit.
        return 0;
    }
}

, , ,


2.ASSERT   #include

int main(int argc, int *argv[]) {
    assert(isdigit(argv[1]));
}

* Assert will terminate the program if argv [1] is not a digit

3.THROW #include

using namespace std;

class Except {};

int main(int argc, int **argv) {
    try {
        isdigit(argv[1]);
        throw Except();
        // this code will not be executed
        // if argv[1] is not a digit
    }
    catch (Except) {
        cout << "argv[1] is not a digit.";
        // handle exception or rethrow
    } 
}

Of course, it is worth noting that throwing an exception will create a stack trace , and all the code between the thrown exception and the block that will catch the exception will NOT be executed.

-1
source

All Articles