0

This is about a cricket match, and I am going to be given some inputs. The first input is going to be a number, which says how many inputs it will be followed by, and each of them would be strings. The characters in each string will represent the outcomes of balls played in that match. The following shows the possible outcomes:

Outcome: Description

N: No ball, W: Wide ball, D: Dead ball, O: Out, 0-6: Runs scored.

For example, an input might be: 3 W123NW6WD64 444WO213 444

Now for each of these 3 series of balls, I have to find out the numbers of legal balls played in that series. The output for this input is expected to be: 6 7 3

I tried to build the algorithm, and everything seemed to be fine, but my code is giving output to a string before it reads one. that is, for the input above, my code outputs: 0 6 7.

Here is my code:

#include <stdio.h>
#include <string.h>

void balls (char* ptr);

int main()
{
    int count;
    scanf ("%d", &count);

    for (int i = 0; i < count; i++)
    {
        char str[100];
        gets (str);
        balls (str);
    }
}

void balls (char* ptr)
{
    int balls = 0;
    int length = strlen (ptr);

    for (int k = 0; k < length; k++)
    {
        switch (*(ptr + k))
        {
        case 'N':
            break;

        case 'W':
            break;

        case 'D':
            break;

        case '\0':
            break;

        default:
            balls++;
            break;
        }
    }

    printf ("%d\n", balls);
}

How do you think I can fix this? Thanks in advance!

Martin
  • 3,960
  • 7
  • 43
  • 43
  • Don't mix formatted I/O (`scanf()`) with line oriented I/O (like `gets()`) on the same stream. They handle whitespace differently, which gives strange interactions (e.g. `scanf()` leaves a newline waiting to be read, and `gets()` then returns immediately - in your code, the first call of `gets()` immediately reads a zero length string). Better to read all your I/O using line-oriented input (i.e. read a whole line) and then parse the string to extract an integral value. Also - DO NOT use `gets()` - it was REMOVED from the C standard in 2011, as its usage is so dangerous. Use `fgets()` instead. – Peter May 18 '21 at 14:15
  • It worked, thanks for explaining! – Md Shahriar Rahman May 19 '21 at 04:46

0 Answers0