-1

the code is not letting me scan a character it ends the program instead,also the unit variable always returns 0 for no matter what the value is given

i tried taking the %s instead of %c which works but the units variable always returns 0 no matter the input

`

#include<stdio.h>
int main()

{
    int x,y,units,n;
    char direction;
    printf("enter the co-ordinates [x] [y]:");
    scanf("%d %d" , &x,&y);
    printf("Enter No. units towards:");
    scanf("%d",&units);
    printf("Enter the [direction]:");
    scanf("%c",&direction);

switch(direction)
{
    case 'N':
    y=y+units;
    break;

    case 'S':
    y=y-units;

}

}

`

  • You should use `" %c"` for reading single characters to get rid of the pending `\n` in the buffer. – Gerhardh Nov 05 '22 at 13:01
  • Your description does not make sense. It does not matter if you use `%s` or `%c` as that You should always check the return value of `scanf`. How would you detect any incorrect input without that? – Gerhardh Nov 05 '22 at 13:03
  • Please provide your exact input when you get `unit==0`. – Gerhardh Nov 05 '22 at 13:04

1 Answers1

0

An optional whitespace character passes to the scanf() function that leads to such unwanted behavior. To suppress it, we discard the following whitespace character like this:

scanf(" %c", &foo);

Note that it does not apply to %s.

Also, ensure that you check the no. of parameters that are correctly passed to the scanf() function and assigned to the respective variables with the following method:

if (scanf("%d %d", &a, &b) != 2) {
  // Either or both of the values are incorrectly assigned.
  return EXIT_FAILURE;
}
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34