Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

How do I convert a number from the command line to an inter using strtol in C?

I started a course in C today and I am not really sure how you would use the strtol function to convert a string of an integer from command line arguments instead of using the atoi function (for some reason, I am not allowed to use the atoi function.

How would I change the following code to use the strtol function instead? If possible, please explain what the variables you create (if any) do with relevance to the strtol function.

int main( int argc, char * argv[] ) {
    int num1 = atoi(argv[1]);
    int num2 = atoi(argv[2]);
    
    printf("num1 = %d, num2 = %d", num1, num2);
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

convert a number from the command line to an integer using strtol

[Found many strtol() posts, yet not a direct good C answer to OP's question on SO.]

Good strtol() usage involves base, errno and the end pointer and testing for various outcomes.

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

int main(int argc, char *argv[]) {
  for (int a = 1; a < argc; a++) { // check command line arguments after argv[0].
    int base = 10; // convert strings as encoded with decimal digits.
    char *endptr; // location to store the end of conversion.
    errno = 0;
    long val = strtol(argv[a], &endptr, base);
    printf("<%s> --> %ld:", argv[a], val);
    if (argv[a] == endptr) {
      printf(" No conversion.
");
    } else if (errno == ERANGE) { // ***
      printf(" Out of `long` range.
");
    } else if (errno) {
      printf(" Implementation specific error %d detected.
", errno);
    } else if (*endptr) {
      printf(" Trailing junk <%s> after the numeric part.
", endptr);
    } else {
      printf(" Success.
");
    }
  }
}

*** Better code uses the value of errno promptly after strtol() to insure it reflects an error due to strtol() and not some later function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...