Search code examples
cinputaddition

How to keep track of a users input in C/C++


I need to add to one to the variables at the bottom every time the user choses the language they prefer. If you can help me complete this tally it would be very helpful. When I run the script all I get is a 0.0000 for all variables at the bottom.

#include <stdio.h>

int main() {

    char ye;
    int lang;
    float clan=0, java=0, pyth=0, mat=0;

    printf("Favorite programming language C(1), Java(2), Python(3), Matlab(4): ");
    scanf("%d", &lang);

    printf("Continue (y/n): ");
    scanf(" %c" ,&ye);

    while (ye == 'y')
    {
        printf("Favorite programming language C(1), Java(2), Python(3), Matlab(4): ");
        scanf("%d", &lang);

        if (lang == '1')
        {
            clan=clan+1;
        }
        else if (lang == '2')
        {
            java=java+1;
        }
        else if (lang == '3')
        {

            pyth=pyth+1;
        }
        else if (lang == '4')
        {

            mat=mat+1;
        }

        printf("Continue (y/n): ");
        scanf(" %c" ,&ye);
    }

    printf("C: %f\n",clan);
    printf("Java: %f\n",java);
    printf("Python: %f\n",pyth);
    printf("Matlab: %f\n",mat);

    return 0;
}

Solution

  • Aside from the mentioned issue with comparing and int to a character, you also have a bug here:

    printf("Favorite programming language C(1), Java(2), Python(3), Matlab(4): ");
    scanf("%d", &lang);
    
    printf("Continue (y/n): ");
    scanf(" %c" ,&ye);
    

    As you can see, you skip the first user input without incr. any of the options.

    A cleaner way to handle the first pass through the loop would be something like this (as you can assume the user will have wanted at least the first pass if they launched the program). Note the initialization of ye, change to int for your tallys, and arguably better indentation and method of incrementation pointed out in some other answers.

    #include <stdio.h>
    int main() {
    
        char ye = 'y';
        int lang;
        int clan=0, java=0, pyth=0, mat=0;
    
        while (ye == 'y')
        {
    
            printf("Favorite programming language C(1), Java(2), Python(3), Matlab(4): ");
            scanf("%d", &lang);
    
            if (lang == 1){
                clan++;
            }
            else if (lang == 2){
                java++;
            }
            else if (lang == 3){
                pyth++;
            }
            else if (lang == 4){
                mat++;
            }
    
            printf("Continue (y/n): ");
            scanf(" %c" ,&ye);
        }
    
        printf("C: %d\n",clan);
        printf("Java: %d\n",java);
        printf("Python: %d\n",pyth);
        printf("Matlab: %d\n",mat);
    
        return 0;
    }