Overview
Artifact ID: | 161014003320e41ac6d325fbd11f34e421e01532e9ac2f933a191746e1f57f3e |
---|---|
Ticket: | 85b7226da1ecf6194342f802ff4361bfc75b8a34 |
Date: | 2023-09-21 17:12:22 |
User: | griffin |
Artifact Attached: | 91f3ee7e87d485d493b0327c29469acd369d4f89d64a23027b0a8844f41e3fbd |
Filename: | cscan.c |
Description: | C program to exercise sscanf() |
Content Appended
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73#include <stdio.h> #include <errno.h> #include <string.h> int main(int argc, char **argv) { int i; if (argc<3) { printf("usage: %s <string-value> <format-string> <value-type:(i|b|d|f|c)>\n" "Uninitialized variables have value of -777, -7.77, or \"BAAD\"\n", argv[0]); return 0; } for(i=1; i<argc; i+=3) { int status; char *str = argv[i]; char *fmt = argv[i+1]; char *type = argv[i+2]; int ival; char cval; double dval; float fval; char remainder[4092]; char fmtbuffer[4092]; sprintf(fmtbuffer, "%s%%s", fmt); ival = -777; dval = -7.77; fval = -7.77; strncpy(remainder,"BAAD",4); switch (type[0]) { case 'i': case 'b': status = sscanf(str, fmtbuffer, &ival, &remainder); if (status < 0) { perror("Error: sscanf returned 0\n"); } else { printf("sscanf(\"%s\", \"%s\", &%s, &remainder) -> returned %d, results %s=%d remainder=\"%s\"\n", str, fmtbuffer, type, status, type, ival, remainder); } break; case 'f': status = sscanf(str, fmtbuffer, &fval, &remainder); if (status < 0) { perror("Error: sscanf returned 0\n"); } else { printf("sscanf(\"%s\", \"%s\", &%s, &remainder) -> returned %d, results %s=%f remainder=\"%s\"\n", str, fmtbuffer, type, status, type, fval, remainder); } break; case 'd': case 'l': status = sscanf(str, fmtbuffer, &dval, &remainder); if (status < 0) { perror("Error: sscanf returned 0\n"); } else { printf("sscanf(\"%s\", \"%s\", &%s, &remainder) -> returned %d, results %s=%f remainder=\"%s\"\n", str, fmtbuffer, type, status, type, dval, remainder); } break; case 'c': status = sscanf(str, fmtbuffer, &cval, &remainder); if (status < 0) { perror("Error: sscanf returned 0\n"); } else { printf("(%d) %s -> %c \"%s\"\n", status, str, cval, remainder); } break; default: printf("Unknown type: %s\n", type); break; } } }