-2

I a working on an assignment that allows the user to input "type" and "weight" and it'll display the cost. Here is the code. I want it to keep running until the user enters 'n'.

main()
{   
    char type,chr;
    float cost,weight;

    do
    {   
        printf("Insert the type of fish: ");  /*inputs type and weight*/ 
        scanf("%c",&type);
        printf("insert weight: ");
        scanf("%f",&weight);

        switch(type)                        
        {
            case 'K':
            case 'k':
                cost=weight*9.00;
                break;
            case 'R':
            case 'r':
                cost=weight*10.00;
                break;
            case 'S':
            case 's':
                cost=weight*12.00;
                break;
            case 'G':
            case 'g':
                cost=weight*8.00;
                break;
            case 'T':
            case 't':
                cost=weight*15.00;
                break;
            default :
                printf("Invalid type\n");
        }
        printf("The cost of fish is:%.2f \n",cost);
        printf("Do you want to continue?Y/N: ");
        scanf(" %c",&chr);
    }
    while(chr == 'Y' || chr == 'y');
}

I have used the do..while loop, it worked fine until I typed in 'y' and I cannot enter the type.

it looked something like this

Nic3500
  • 8,144
  • 10
  • 29
  • 40
Firas
  • 1
  • 1
    Hi! Welcome to StackOverflow! I would suggest you to improve the quality of your question by: keeping your title to a minimum, using correct formatting / indentation. See also [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – norok2 Sep 20 '18 at 15:08
  • Use `fgets()` (possibly followed by `sscanf()`) for user input. `scanf()` is rather poor when it comes to error treatment/recovery and it's awkward for managing whitespace. Your immediate problem is the still in the input buffer after `scanf(" %c", &chr);`. – pmg Sep 20 '18 at 15:14
  • 1
    I think this is an issue of scanf being skipped. Please se this answer. https://stackoverflow.com/a/29775377/5774004 – Sreeragh A R Sep 20 '18 at 15:14
  • @SreeraghAR i think this seems to be the problem,all i had to do is put space in "%c".Thank you soo much!!!! – Firas Sep 20 '18 at 15:27

1 Answers1

0

Reading types from the stdin stream assumes you know exactly what is next in the stream. As Streeragh mentions, you likely have a newline as the next input character. You can triage this by dumping out what chr is (try it in hex, like %0x). The mentioned article also offers good advice: Input the text as %s (or use readline) and then parse out the input. Look into strtok. And also be aware that stdin can be redirected from a pipe (i.e out.exe < sampleinput.txt) Cheers.

Micromuncher
  • 903
  • 7
  • 19