Hi guys I am looking to go through C then transition to C++ later this year. I am having a minor problem with switch statement and I am not in a position to ask anyone as there are no tech savvy that I know. So I thought it was better to ask here.
So I am trying to get input from the user with the switch statement, once the user has entered a letter for what he is looking to purchase, they should be summed up but they dont and they just increment all the last three input by 1 ( ie for artichokes, beets, and carrots). I hope that someone can show me what I am not seeing. Thanks!!!

// abcmail.c -- This is a program that calculates all fo ABC Mail Order Grocery activities
#define ARTICHOKE 2.05
#define BEET 1.15
#define CARROT 1.19

#include <stdio.h>
int main (void)
{

    // Declaring my Variables
    char ch;                        // Input character
    int artichoke_count;            // artichoke counter
    int beet_count;                 // beet counter
    int carrot_count;               // carrot counter

    //  Initializing my variables
    artichoke_count = 0;
    beet_count = 0;
    carrot_count = 0;

        printf("Enter the letter a for artichoke, b for beet and c for carrot and q to quit: ");

    while((ch = getchar()) != 'q' )
    {
        int _artichoke;
        int _beet;
        int _carrot;

        if (islower(ch))
        {
            switch(ch)
            {
                case 'a':
                {
                    printf("Enter the number of arhitokes you need: ");
                    scanf("%d", &_artichoke);
                    artichoke_count+=_artichoke;
                    break;
                }

                case 'b':
                {
                    printf("Enter the number of beets you need: ");
                    scanf("%d", &_beet);
                    beet_count+=_beet;
                    break;
                }

                case 'c':
                {
                    printf("Enter the number of carrots you need: ");
                    scanf("%d", &_carrot);
                    carrot_count+=_carrot;
                    break;
                }

                default:
                printf("I am only accepting a for arhitokes, b for beets and c for carrots");
                break;
            }   // end of switch
        } // end of if

    } // end of while loop

    printf("You have entered %d artichokes, %d beets, and %d carrots", artichoke_count, beet_count, carrot_count);

    return 0;
}

Recommended Answers

All 4 Replies

Not sure why you'd be getting that behavior. What is the exact input you are using? What is the corresponding output?

Your code runs fine for me. The only thing I can think of that might be happening is that between getchar and scanf and whatever you are typing in, something is getting read in wrong. Try clearing the stdin buffer by sticking this line at the bottom and top of your while loop.

fseek(stdin,0,SEEK_END);

http://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c

I agree with AssertNull, it's very likely the newline character mucking things up. Your compiler (or compiler settings) probably aren't zeroing out local variables while AssertNull's is, which explains the code working in one place but not another. You can verify this by initializing _artichoke, _beet, and _carrot to 0.

Typically, it's not wise to mix formatted and unformatted input (ie. getchar and scanf) due to differences in handling of whitespace. IIRC, the %d format modifier should skip whitespace before attempting a character extract, though I don't recall if that's a hard requirement or just something that a lot of compilers do (it's been a while since I read the standard ;p). You can force it by putting a leading space in your format string:

scanf(" %d", &_artichoke);

fseek(stdin,0,SEEK_END);

Yeah, that's not guaranteed to work. There's not a complete standard way to "flush" stdin in C; the best you can get is some variation of this:

int c;

do
{
    c = getchar();
} while (c != '\n' && c != EOF);

It's perfectly functional, provided the stream is not currently empty. If it is empty, getchar will block for unnecessary input and there's no standard way to get around that particular issue.

You are actually masking the error the way you have the code. If you copy the printf prompt from line 21 and stick it on line 62, you'll see that you are going through the loop more times than you may realize. Two, if you delete the test for islower by deleting lines 29, 30, and 61, you might also get some printouts that are useful. If the everything is going right, you'd want to delete those lines anyway. If I don't enter 'a', 'b', or 'c', I WANT that error message telling me I need to enter 'a', 'b', or'c'. The way you have it now, I could keep entering '5' thinking that I was entering the number of beets and not quite realize that there was a problem (no prompt, no error message). With those changes, I ran your program, answered b, hit enter, was prompted to enter the number of beets, entered 5, then hit enter, then I was prompted again for a, b, or c, then line 58 printed out, which means that the program did not stop at the top of the while loop for me to enter 'a', 'b', or 'c' because there is a newline in the input stream that is gobbled up by the getchar statement at the top. It's actually a fairly nice bug as it helpfully gobbles up all the white space, but if it was not on purpose (and I assume it was not), it probably means the program is not functioning as you expect and you didn't realize it, which is a bad thing.

Thank you guys I saw the errors and they were very silly :D.
The code should have looked like this:

// abcmail.c -- This is a program that calculates all fo ABC Mail Order Grocery activities
#define ARTICHOKE 2.05
#define BEET 1.15
#define CARROT 1.19

#include <stdio.h>
#include <ctype.h>
int main (void)
{

    // Declaring my Variables
    char ch;                        // Input character
    int artichoke_count;            // artichoke counter
    int beet_count;                 // beet counter
    int carrot_count;               // carrot counter

    //  Initializing my variables
    artichoke_count = 0;
    beet_count = 0;
    carrot_count = 0;

    /************************************************* PART 1: Collecting User Input *********************************************/
    printf("Enter the letter a for artichoke, b for beet and c for carrot and q to quit: ");

    while((ch = getchar()) != 'q' )
    {

        int artichokes; // Will collect artichokes numbers from the user
        int beets;      // Will collect beets numbers from the user
        int carrots;    // Will collect carrot numbers from the user

        if ('\n' == ch) // What this does is put a new line without affecting the program because the '\n' 
            continue;   // will be regarded as a character and placed in default section

            ch = tolower(ch); // make the input characters to lower case if the user enters uppercase

            switch(ch)
            {
                case 'a':
                {
                    printf("Enter the number of arhitokes you need: ");
                    scanf("%d", &artichokes);
                    artichoke_count += artichokes;
                    break;
                }

                case 'b':
                {
                    printf("Enter the number of beets you need: ");
                    scanf("%d", &beets);
                    beet_count += beets;
                    break;
                }

                case 'c':
                {
                    printf("Enter the number of carrots you need: ");
                    scanf("%d", &carrots);
                    carrot_count += carrots;
                    break;
                }

                default:
                printf("I am only accepting a for arhitokes, b for beets and c for carrots");
                break;
            }   // end of switch

            printf("Enter the letter a for artichoke, b for beet and c for carrot and q to quit: ");

    } // end of while loop

    printf("You have entered %d artichokes, %d beets, and %d carrots", artichoke_count, beet_count, carrot_count); // testing 
   /******************************************** End of Part 1 ******************************************************************/
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.