Reputation: 23
#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?
Upvotes: 1
Views: 125
Reputation: 59617
You aren't allowing much space for those two strings: only 2 char
for 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:
char wunit[3]; // weight unit
char hunit[3]; // height unit
Your code works fine for me with larger arrays.
Upvotes: 2
Reputation: 10104
Because you're trying to but a two character string inside a 2 character array. Strings should always end with '\0', so you should do:
char wunit[3]; // weight unit
char hunit[3]; // height unit
For example, the wunit array would have: ['l', 'b', 0]
Upvotes: 1
Reputation: 40246
Using %s
in scanf
is always a bad idea, for the same reason that gets
is always a bad idea. You must specify a fixed buffer size; yours, of 2, is absurdly small, but more generally, you cannot control how many characters will be in the input stream, so your program will be susceptible to buffer overflow.
Some ways to fix this:
Prefix %s
with some length, i.e. "%2s
". This will put a maximum length on the amount of characters copied.
Use fgets
to read the whole line into a string buffer (with some arbitrary maximum), then you have some bounds to the value you wish to read with %s
. You can even use sscanf
to do it.
Use something like readline
which will allocate arbitrary amounts of characters to read the line.
Upvotes: 1
Reputation: 64414
You are missing a \n
in the last printf()
statement, and since stdout is probably buffered, it is only written to the screen at end-of-line.
Upvotes: 1