char with switch statment

I'm having trouble with the switch statement. When i input c,t or b its skips the call function and goes to the default. From what i can tell there is no error but clearly that is not the case.

1
2
3
4
5
6
7
8
9
10
11
12
13
printf("Type of vehicle (c - t - b)\t\t");
	scanf("%c\n", &vehicle);

	switch (vehicle)
	{
		case 'c': carcharges (hourin, minin, hourout, minout, charge, minutes, hours);
					break;
		case 't': truckcharges (hourin, minin, hourout, minout, charge, minutes, hours);
					break;
		case 'b': buscharges (hourin, minin, hourout, minout, charge, minutes, hours);
					break;
		default: printf("invalid\n");
	}

Are you definitely inputting a lower-case character? ("C" is not the same as "c", as far as the switch statement is concerned).
yeah that's what i thought was wrong at first but i tried both upper and lowercase
Have you tried printing the value of 'vehicle' (around line 3), to see what actually is being input? (I'm guessing the scanf() isn't doing what you expect...).

ETA: under MinGW, I had to remove the \n to get it to read a single character:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int main( int ac, char *av[] )
{
  char vehicle = 0;
  
  printf("Type of vehicle (c - t - b)\t\t");
  scanf("%c", &vehicle);

  printf( "Vehicle = '%c'\n", vehicle );

  return 0;
}
Last edited on
that was a good idea. i tried it and it just comes back blank, so for some reason my scanf isn't scanning.
Try removing the \n from the scanf() string. From http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ I believe you may be running into a problem of telling scanf to "read a character, then read any number of whitespace characters until you get to the next non-whitespace character" (at least, that was the way my quick MinGW program above behaved, until I removed the \n).
Thanks that worked i don't know why the \n effected it but thank you for the help
scanf("%c\n",&vehicle);

'%c' states that only one character should be read. While executing the above statement a newline character '\n' is printed first (that is why your cursor might have gone to next line while waiting for input from u). After that you enter your input, that may be 'c' or 't' or 'b'....

So there are 2 characters, first one is newline ('\n') and second one is what you entered(c or b or t)....
due to "%c", only first character is saved in vehicle, that is newline.....that is why it does not matches with any of the switch cases....
Topic archived. No new replies allowed.