I want to get the user input for variable L, but the scanf function is not working, and the program will jump and print the next cost statement and exit if I try to input anything.
I am new to C, and hope can get some help here. Thanks. Code below:
#include <stdio.h>
#include <conio.h>
int main()
{
float L = 0; // L is litre
float gallon;
gallon = 3.785 * L;
char x[2] = {'u', 'd'}; // u is unleaded and d is diesel
float cost;
printf("Hello, welcome to PetrolUpHere!!\n");
printf("Would u like unleaded or diesel fuel?");
scanf("%s", &x[2]);
printf("Enter the litre you want to fuel:");
scanf("%.2f", &L); //SCANF NOT WORKING
switch (x[2]) {
case 'u':
cost = 1.98 * gallon;
printf("The cost is :%.2f ", cost);
break;
case 'd':
cost = 1.29*gallon;
printf("The cost is :%.2f ",cost);
break;
}
getch();
return 0;
}
There are a number of problems here:
I imagine you wanted to read a string into the variable
x. Instead, you’re saying “read a string into memory 2 positions past wherexpoints”. In this case that memory will be out of bounds. You should do this, since you only care about one character:Your
switchstatement is similarly broken;x[2]is again out of bounds. Useinputfrom the above code instead.As others have pointed out, using
%.2fis not what you want to do when reading in L. Use%finstead. Generally you should only do something like that with format specifiers when printing out variables, rather than reading them in. Eventually you won’t be usingscanfanyway, since it’s not a particularly safe way of getting input.Finally: it seems like your understanding of how C strings work is shaky at best. This is understandable, since this is a fairly confusing topic for anyone who hasn’t worked in C before, and especially for novice programmers. Here’s one explanation; I’m sure you can find many more, probably better ones if you look.