Check if a string has only numerals and do conversion if it is true


$ls
ascii-table     avg-with-garbage.txt  env-var.c      functions_ver1    mph-to-kph
ascii-table.c   case-changer          env-var-set    functions_ver1.c  mph-to-kph.c
ascii-table.md  case-changer.c        env-var-set.c  functions_ver2    mph-to-kph_v2.c
avg.txt         env-var               exist.sh       functions_ver2.c  output.c
$./mph-to-kph 
564
907.7
$cat mph-to-kph.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char mph[10] = { 0 };

    while(fgets(mph, sizeof(mph), stdin) != NULL)
    {
        /* Check if mph is numeric 
         * (and do conversion) */
        if( strspn(mph, "0123456789.-\n") == 
            strlen(mph) )
        {
            printf("%.1f\n", (atof(mph)*1.60934) );
        }
        /* If mph is NOT numeric, print error 
         * and return */
        else
        {
            fprintf(stderr, "Found non-numeric" 
                " value\n");
            return 1;
        }
    }
    return 0;
}
$

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: