0

My program should accept 2 int value as the number and the position at which it should be added. After that it should ask wheather you want to insert more Y/N? But my program dosen't take the input of char instead takes a garbage value and keeps on asking for numbers only.

I have tried using seperate scanf for each input.

#include<stdio.h>
#include<conio.h>
void main()
{
int x,n;
char opt;
clrscr();
do{
    printf("\nEnter the no. to be added and the position:");
    scanf("%d%d",&x,&n);
    printf("Do you want to insert more elements Y/N?");
    scanf("%c",&opt);
    printf("opt=%c x=%d n=%d",opt,x,n);
}while(opt!='N'&&opt!='n');
}

My o/p should be the value of each variables instead I get a garbage value in opt and the loop continues as it isn't 'n'.

  • 2
    You're not checking the return value from `scanf()` to see if each call actually worked. You need to do that. – Andrew Henle Aug 01 '19 at 11:21
  • 1
    I know there's a duplicate somewhere, but can't find it right now. Anyway, the problem is that the "garbage" you read into `opt` is the newline from the `Enter` key you pressed for the previous input. You need to skip it, by adding a leading space in the format string (as in `" %c"`). – Some programmer dude Aug 01 '19 at 11:22
  • 1
    On a couple of unrelated notes, to make things easier: Use [`fgets`](https://en.cppreference.com/w/c/io/fgets) to read full lines into strings, and use `sscanf` to parse the strings; Always check what `scanf` (of `sscanf`) [*returns*](https://en.cppreference.com/w/c/io/fscanf#Return_value); And use e.g. [`tolower`](https://en.cppreference.com/w/c/string/byte/tolower) to simplify the loop condition (`tolower(opt) != 'n'`). – Some programmer dude Aug 01 '19 at 11:25
  • https://stackoverflow.com/questions/3744776/simple-c-scanf-does-not-work – Babajan Aug 01 '19 at 11:33
  • "I get a garbage value in opt and the loop continues as it isn't 'n'." --> only describes the output. Post the exact input used and the exact output seen. – chux - Reinstate Monica Aug 01 '19 at 11:47
  • I answered a question similar to this before and recommended to use fgets instead of scanf. Have a look at it: https://stackoverflow.com/questions/56203851/when-i-run-my-code-twice-after-a-while-dowhile-the-scanf-does-not-work-as-int/56203960#56203960 And here https://stackoverflow.com/questions/56213608/i-cant-take-input-from-user-properly/56213939#56213939 – Irelia Aug 01 '19 at 12:56

1 Answers1

0

The new line character is being read into your variables.

Change this line:

 scanf("%c",&opt);

To this:

 scanf(" %c",&opt);

The space consumes the new line character. This is only necessary for your " %c" format specifier. The "%d" does not require the space.

ryyker
  • 22,849
  • 3
  • 43
  • 87