+ 1

My code starts to be executed even before getting the first necessary input

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!

18th May 2021, 2:17 PM
Md Shahriar Rahman
Md Shahriar Rahman - avatar
1 Odpowiedź
0
I have tested your code and it pauses for first user input. what is your environment for executing? maybe a previous input is remained in buffer of stdin use this command just before your first scanf() fflush(stdin);
18th May 2021, 7:04 PM
Hossein Mohtashami
Hossein Mohtashami - avatar