0
0
Cprogramming~5 mins

Parsing numeric arguments

Choose your learning style9 modes available
Introduction

Parsing numeric arguments means reading numbers given as text and turning them into actual numbers the program can use.

When your program gets numbers from the command line and needs to use them.
When reading numbers from a text file or user input.
When converting strings to numbers for calculations.
When validating that input is a proper number before using it.
Syntax
C
#include <stdlib.h>

int number = atoi("123");

// or

long number = strtol("123", NULL, 10);

atoi converts a string to an int but does not handle errors well.

strtol is better because it can detect invalid input and supports different number bases.

Examples
Simple use of atoi to convert "42" to the number 42.
C
#include <stdlib.h>

int main() {
    int num = atoi("42");
    return 0;
}
Using strtol to parse a number and check if the whole string was a valid number.
C
#include <stdio.h>
#include <stdlib.h>

int main() {
    char *endptr;
    long num = strtol("123abc", &endptr, 10);
    if (*endptr != '\0') {
        printf("Invalid characters after number: %s\n", endptr);
    } else {
        printf("Number is %ld\n", num);
    }
    return 0;
}
Sample Program

This program reads the first command line argument, tries to convert it to a number, and prints it. If the input is not a valid number, it shows an error.

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

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Please provide a number as argument.\n");
        return 1;
    }

    char *endptr;
    long number = strtol(argv[1], &endptr, 10);

    if (*endptr != '\0') {
        printf("Error: '%s' is not a valid number.\n", argv[1]);
        return 1;
    }

    printf("You entered the number: %ld\n", number);
    return 0;
}
OutputSuccess
Important Notes

Always check if the input is valid after parsing to avoid errors.

Use strtol instead of atoi for safer parsing.

Remember to include stdlib.h for these functions.

Summary

Parsing numeric arguments means converting text to numbers.

atoi is simple but unsafe; strtol is safer and better.

Always check for invalid input after parsing.