+ 2
How do I improve my code? *Need to debug
Hey guys, I know I shouldn't be using gets() for reading strings, but I'm facing a little problem if I try to do it with fgets(). In the code, (please check the code first) if the mentioned input is passed, the output with fgets() is: 5 BALLS 5 BALLS But in the first line, the output should be 4 BALLS. What is the problem with fgets() only with the first case? Gets() works just fine here, but I don't want to use that. https://code.sololearn.com/c3A22a10a05a/?ref=app
1 Resposta
+ 1
Can you try the following?
For input:
2
WD621O
6102ON
The following outputs:
4 BALLS
5 BALLS
Some changes explained:
- removed your c_count variable since the str variable could fill the same role with 1 less variable.
- replaced gets with fgets in main since fgets is more generally recommended and makes buffer length explicit.
- replaced your switch statement with a much shorter call to strchr.
- removed your length variable in the balls function since you could simply check for '\0' with no extra code.
- incremented ptr instead of keeping your k variable.
void balls (char* ptr);
int main()
{
int count;
char str[100];
fgets (str, 100, stdin);
count = atoi(str);
for (int i = 0; i < count; i++)
{
fgets (str, 100, stdin);
balls (str);
}
}
void balls (char* ptr)
{
int balls = 0;
for (; *ptr != '\0'; ptr++)
{
if (strchr("WDN\r\n", *ptr) == NULL)
balls++;
}
int overs = balls / 6;
balls %= 6;
if (overs == 0)
{
if (balls == 1)
{
printf ("1 BALL");
}
else
{
printf ("%d BALLS", balls);
}
}
else
{
if (overs == 1)
{
printf ("1 OVER");
}
else
{
printf ("%d OVERS", overs);
}
if (balls == 1)
{
printf (" 1 BALL");
}
else if (balls > 1)
{
printf (" %d BALLS", balls);
}
}
printf ("\n");
}