crispeeweevile

echo_input_0717_0504

Jul 17th, 2023
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | Source Code | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. /*
  6. * Basically this program was simply made as practice
  7. * The only job of the program is to "echo" what the user inputs back,
  8. * And possibly print a number, if it was there.
  9. */
  10.  
  11.  
  12. int main() {
  13.     int a_num = 0;
  14.     int boofer_size = 200;
  15.     // Use calloc to allocate an array which can hold 200 characters
  16.     char *boofer = calloc(sizeof(char), boofer_size);
  17.     // Did the allocation fail?
  18.     if(boofer == NULL) {
  19.         // Skip to the end of the program after printing a warning
  20.         printf("Failed to allocate buffer!");
  21.         goto end;
  22.     }
  23.    
  24.     // Use fgets() to get the user input
  25.     // I heard this was the safest way to do it
  26.     char* success = fgets(boofer, boofer_size, stdin);
  27.     if(success != NULL) {
  28.         // If we succeeded, then use sscanf_s() to get leading number
  29.         int items_assigned = sscanf_s(boofer, "%d", &a_num);
  30.         printf(boofer);
  31.        
  32.         if(items_assigned == 1) {
  33.             // If we got the number, print it.
  34.             printf("%d", a_num);
  35.         }
  36.  
  37.         // Successfully free the memory knowing nothing could go wrong??
  38.         free(boofer);
  39.     }
  40.  
  41.     // Return 0 to indicate everything went fine
  42. end:
  43.     return 0;
  44. }
Add Comment
Please, Sign In to add comment