#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
char wunit[2]; // weight unit
char hunit[2]; // height unit
double weight, height;
printf("Enter the body weight: ");
scanf("%lf%s", &weight, &wunit); // input weight and unit eg. 150lb
printf("Enter the height: ");
scanf("%lf%s", &height, &hunit); // input height and unit eg. 5.65 ft
printf("The height unit: %s\n", hunit);
printf("The weight unit: %s", wunit);
return 0;
}
This code only prints out the height unit, and not the weight unit. What can I do to fix it?
You aren’t allowing much space for those two strings: only 2
charfor each. Note that C strings also require space for a null-terminating character to mark the end of the string.With the null-terminating character, your two strings can each only properly hold a single character. When you input e.g. “lb” and “ft”, you’re using data outside the bounds of your arrays. Change the size of your arrays to (at least) 3, and see if the code prints out both units correctly:
Your code works fine for me with larger arrays.