Beginning C guy.... need help on first FUNCTION assignment

Discussion in 'C' started by schweny, Jan 21, 2011.

  1. schweny

    schweny New Member

    Joined:
    Jan 21, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    This is suppose to calculate the BMI of someone. I have Hints but I still don't really know where to start... Can anyone give me some suggestions?

    Code:
    // hint: you're going to need to include another library to make the file functions below work right.
    
    /*
     * Task: create a program that reads a bmi file and outputs bmi to stdout
     *
     * The BMI file is formatted like this:
     * 105, 66
     * 104.8, 58.2
     *
     * Where the first column is the weight in pounds and the second column is the height in inches
     *
     *
     * The output should look like this:
     * Height: 66 inches; Weight: 105 lbs; BMI: bla
     *
     */
    
    int main(int argc, char *argv[]) {
        if (argc < 2) {
            printf("Missing filename. Usage: %s <filename>\n", argv[0]);
        }
    
        char line[20]; // variable to store one line at a time from the file
        FILE * infile_fp; // variable to store the file pointer
        infile_fp = fopen(argv[1], "r"); // open the file passed on the command line
    
        // read the file one line at a time
        while (fgets(line, 20, infile_fp)) {
            float weight, height;
            // write a line here that breaks the weight and height out of the string
            // hint, try sscanf()
    
            printf("Height: %4.2f inches; Weight: %4.2f lbs; BMI: %4.2f\n", height, weight, bmi(weight, height));
     
  2. DRK

    DRK New Member

    Joined:
    Apr 13, 2012
    Messages:
    44
    Likes Received:
    3
    Trophy Points:
    0
    Function counting BMI
    Code:
    float bmi(float weight, float height) {
        return (weight * 703) / (height * height);
    }
    You should end program in case of error
    Code:
    if (argc < 2) {
        ...
        return -1;
    }
    ...
    if (!infile_fp) {
        printf("Error opening file %s\n", argv[0]);
        return -2;
    }
    sscanf() format in this case
    Code:
    sscanf(line, "%f, %f", &weight, &height);
     
  3. DRK

    DRK New Member

    Joined:
    Apr 13, 2012
    Messages:
    44
    Likes Received:
    3
    Trophy Points:
    0
    Correction
    Code:
    printf("Error opening file %s\n", argv[1]);
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice