0

Here is the code

//WAP in Co convert a binary or octal to a decimal number depending on user choice.
#include <stdio.h>
#include <math.h>
int conversion(int number,int base);
int main(void){
    int number,base,decimal;
    char choice;
    printf("Enter the number:");
    scanf("%d",&number);
    printf("Enter 'b' for binary or 'o' for octal:");
    scanf("%c",&choice); //Problem occuring here 
    if(choice=='b')
        base=2;
    base=8;
    decimal=conversion(number,base);
    printf("Decimal number:%d",decimal);
    return 0;
}

int conversion(int number,int base){
    int reminder;
    int decimal=1;
    int i=0;
    while(number>=0){
        reminder=number%base;
        decimal=(decimal*reminder)*pow(base,i);
        number/=10;
        i++;
    }
    return decimal;
}
  • 1
    What is the problem? Is your problem that second scanf not waiting for user to enter choice? – sps Jul 09 '16 at 06:19
  • Problem is that the value is not accepting from keyboard at the second scanf . – Preetam Rawat Jul 09 '16 at 06:23
  • `scanf("%c",&choice)` --> `scanf(" %c",&choice);` – BLUEPIXY Jul 09 '16 at 06:24
  • It is not clear what you are trying to say. Do you mean that you are entering some value but the program is refusing to accept it? Or do you mean that program is not giving you a chance to enter a choice? – sps Jul 09 '16 at 06:24
  • I mean that I'm entering some value and program is refusing to accept – Preetam Rawat Jul 09 '16 at 06:27
  • This usually happens when there is a trailing newline `\n` remaining from previous entries. You can try using `scanf("%c",&choice)` twice, or like BLUEPIXY mentioned, you can change your `scanf("%c",&choice)` to `scanf(" %c",&choice)`, i.e preceed `%c` by a blank space. – sps Jul 09 '16 at 06:27
  • Thanks it worked but one more problem occured after that my program is not runnig its just got paused after that – Preetam Rawat Jul 09 '16 at 06:31
  • Use a debugger or debug print statements to trace the execution of your program. That's just debugging 101. If you still can't work it out then post a new question with all the relevent information - that is give precise input and exact output. – kaylum Jul 09 '16 at 06:33

1 Answers1

1

You have two scanf() and after the one some character is left out to read. you can use getchar() before the next scaf() it should take the next input

printf("Enter 'b' for binary or 'o' for octal:");
getchar();
scanf("%c",&choice);

Inside the conversion function you have while loop with a condition causes it go in infinite loop.Dividing a positive number by 10 minimum you can get is 0. use the below code:

while(number>0)

Also, if condition you have after the second input is useless. since you assign 8 to base anyway.

Denis
  • 1,219
  • 1
  • 10
  • 15