/* * program to show how strtol/strtod work * enter number when prompted * * Matt Bishop, ECS 36A * * April 30, 2024 * -- original version */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* * macro */ #define BUFFERSIZE 1024 /* size of input buffer */ /* * main routine */ int main(void) { char buf[BUFFERSIZE]; /* input buffer */ long i; /* integer read in */ char *eol; /* char following the end of integer */ double f; /* double read in */ char *eod; /* char following the end of double */ /* * read in a line and process it */ printf("How strtol/strtod work:\n> "); while(fgets(buf, BUFFERSIZE, stdin) != NULL){ /* clobber the trailing newline to keep the output clean */ if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0'; /* convert to integer and print it */ i = strtol(buf, &eol, 10); printf("\'%s\' is the integer %ld; rest of string: \'%s'\n", buf, i, eol); f = strtod(buf, &eod); printf("\'%s\' is the double %f; rest of string: \'%s'\n", buf, f, eod); printf("> "); } /* clean up the end of the output */ putchar('\n'); /* * done! */ return(0); }
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |