Menu

C code problem

pat kob
2009-09-22
2012-09-26
  • pat kob

    pat kob - 2009-09-22

    The code here is suppose to let you enter your age and then convert it to days
    but when I run it, I enter an age and it just stops. please tell me what I am
    doing wrong.

    include <cstdlib>

    include <iostream>

    using namespace std;

    int main(int argc, char *argv)
    {
    int days_in_year;
    days_in_year = 365;
    printf("how old are you.\n");
    scanf("%d") / days_in_year;
    printf("\nyou are %d days old.\n");
    system("PAUSE");
    return EXIT_SUCCESS;
    }

     
  • cpns

    cpns - 2009-09-22

    Did you mean to post something readable perhaps? Use the forum's new code
    mark-up (select the text and click the "Code Sample" button:
    include <cstdlib>
    include <iostream>

    using namespace std;

    int main(int argc, char *argv)
    {
    int days_in_year;
    days_in_year = 365;

    printf("how old are you.\n");
    scanf("%d") / days_in_year;
    printf("\nyou are %d days old.\n");
    system("PAUSE");
    return EXIT_SUCCESS;
    }

    The scanf() call does not return the value entered, it returns teh number fo
    fields successfully converted and stored in the variables referenced by its
    arguments (you failed to pass it any, so your code crashed). Read the . The
    example given there is very similar to yours.

    http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

     
  • cpns

    cpns - 2009-09-22

    Oops. Sourceforge's new mark-up not yet perfect!:

    include <cstdlib>
    include <iostream>
    using namespace std;

    int main(int argc, char *argv)
    {
    int days_in_year;
    days_in_year = 365;

    printf("how old are you.\n");
    scanf("%d") / days_in_year;
    printf("\nyou are %d days old.\n");
    system("PAUSE");
    return EXIT_SUCCESS;
    }

    Note you also have too few arguments to printf(). %d is not a magic variable,
    it is a format specifier - you have to supply a value (or a variable in the
    case of scanf().

    Set teh -Wall -Wformat -Werror compiler options, and the problems in your code
    will be spotted and reported by the compiler.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.