Advertisement
silver2row

Learning_More

Feb 5th, 2022
969
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. #define _XOPEN_SOURCE 500
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6.  
  7. void printHelp(FILE *stream, char progname[]);
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11.    char mph[10] = { 0 };
  12.    int opt;
  13.    int cont = 0;
  14.  
  15.    /* Parse command-line options */
  16.    while ((opt = getopt(argc, argv, "ch")) != -1)
  17.    {
  18.       switch(opt)
  19.       {
  20.          case 'h':
  21.             printHelp(stdout, argv[0]);
  22.             return 0;
  23.          case 'c':
  24.             cont = 1;
  25.             break;
  26.          default:
  27.             printHelp(stderr, argv[0]);
  28.             return 1;
  29.       }
  30.    }
  31.  
  32.    while(fgets(mph, sizeof(mph), stdin) != NULL)
  33.    {
  34.       /* Check if mph is numeric
  35.        * (and do conversion) */
  36.       if( strspn(mph, "0123456789.-\n") ==
  37.             strlen(mph) )
  38.       {
  39.          printf("%.1f\n", (atof(mph)*1.60934) );
  40.       }
  41.       /* If mph is NOT numeric, print error
  42.        * and return */
  43.       else
  44.       {
  45.          fprintf(stderr, "Found non-numeric "
  46.             "value\n");
  47.          if (cont == 1) /* Check if -c is set */
  48.          {
  49.             continue; /* Skip and continue if
  50.                        * -c is set */
  51.          }
  52.          else
  53.          {
  54.             return 1; /* Abort if -c is not set */
  55.          }
  56.       }
  57.    }
  58.    return 0;
  59. }
  60.  
  61. void printHelp(FILE *stream, char progname[])
  62. {
  63.    fprintf(stream, "%s [-c] [-h]\n", progname);
  64.    fprintf(stream, " -c continues even though a non"
  65.       "-numeric value was detected in the input\n"
  66.       " -h print help\n");
  67. }
  68.  
  69. From: https://github.com/PacktPublishing/Linux-System-Programming-Techniques
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement