#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    26
    Rep Power
    0

    Help with C program not working.


    I am learning C and im at the number variables but when i try to run my program it says program has stopped working. Any help would be appreciated. Also i am using codeblocks.Also can somebody tell me what format specifiers i need to use with int.

    Below is the source code.

    #include <stdio.h>
    #include <stdlib.h>

    int main()

    {
    int age;
    char years[10];

    printf("How old was Mat? ");
    gets(years);
    age=atoi(years);
    printf("Mat was %s years old.\n",age);
    return(0);
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    The scanf()/printf() format specifiers must match your variable's type.

    Code:
    int age; 
    ...
    printf("Mat was %s years old.\n",age); 
    
    return(0);
    Does your format specifier "%s" match your variable type (Int)?

    Also stop using gets() this function is very unsafe. I suggest you start using fgets() instead.


    Jim
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    26
    Rep Power
    0
    Thank you i will use scanf() instead of gets()
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,162
    Rep Power
    2222
    scanf is just as unsafe when you read in a string. No way to prevent buffer overflow, a very common hacker exploit.

    Rather, use scanf to convert the input directly to int (ie, use scanf to replace both the gets and the atoi, which has its own problems), or use fgets to read in an entire line of input safely and then apply sscanf to that string.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    scanf is just as unsafe when you read in a string. No way to prevent buffer overflow, a very common hacker exploit.
    Actually scanf() can be used to safely retrieve a string, by using the width modifier to limit the number of characters retrieved.

    Code:
    char myString[10];
    scanf("%10s", myString);
    However in this case using scanf() or fgets()/sscanf() to read the input directly into the number is a much better alternative.

    Jim

    Comments on this post

    • dwise1_aol agrees : LIve and learn. I work almost exclusively in embedded, so my only scanf experience has been researching for problems on this forum.

IMN logo majestic logo threadwatch logo seochat tools logo