简体   繁体   中英

C count numbers entered separated by commas

I have a code that checks if number is odd or even. I use char to input and separate each number with commas. Everything works great, but I need to count how many numbers have been entered and how many of them are even numbers. I ran into a wall because of commas. I tried to search google, but my english is not so good and I can't find such function. Maybe I should loop number entries until user simply press enter to start checking even numbers and odd numbers. My code so far:

char str[256];
 fgets (str, 256, stdin);
    char *pt;
    pt = strtok (str,",");
    while (pt != NULL) {
        int a = atoi(pt);

        if (a%2 == 0)
        {
            printf("Number is even\n");

        }
        else
        {
            printf("Number is odd!\n\n");
        }
        printf("%d\n", a);
        pt = strtok (NULL, ",");
    }

If we use variable++ that means increment value of variable by 1.

char str[256];
fgets (str, 256, stdin);
char *pt;
int odd_count = 0,even_count = 0;
pt = strtok (str,",");
while (pt != NULL) {
    int a = atoi(pt);

    if (a%2 == 0)
    {
        printf("Number is even\n");
        even_count++;
    }
    else
    {
        printf("Number is odd!\n\n");
        odd_count++;
    }
    printf("%d\n", a);
    pt = strtok (NULL, ",");
}
printf("Count of even numbers in the sequence is %d",even_count);
printf("Count of odd numbers in the sequence is %d",odd_count);
printf("Total numbers in the sequence is are %d",even_count + odd_count);

As mentioned in the comments, as you read in each number count the total number of values read in. Then when you do the check for an even number, increments another counter for that:

int countTotal = 0, countEven = 0;
while (pt != NULL) {
    int a = atoi(pt);

    countTotal++;
    if (a%2 == 0)
    {
        printf("Number is even\n");
        countEven++;
    }
    else
    {
        printf("Number is odd!\n\n");
    }
    printf("%d\n", a);
    pt = strtok (NULL, ",");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM