I'm writing a piece of code in C that iterates T times and each time takes as input the text of a little song on which it will perform some counting operation (counting the length of each word). For now I'm just testing if the input works, and it doesn't.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SONG_SIZE 501
int main(void){
int T;
scanf("%d", &T);
while(T--){
char* song = malloc(MAX_SONG_SIZE);
if(song == NULL){
printf("malloc failed");
return 1;
}
fgets(song, MAX_SONG_SIZE, stdin);
printf("foo\n");
free(song);
}
return 0;
}
I'm using fgets() because of the spaces among the words, and dynamic memory allocation because I can't just use one array for all the songs, characters from the previous iteration would remain in the array.
But there's a problem. It skips the fgets() in the first iteration, writing only "foo" and without waiting for me to insert a string.
This is an example of how it prints with initial input "3":
3
foo
this is a test
foo
another test
foo
With substituting printf("foo\n");
with printf("<<%s>>\n", song);
the output is this:
3<br>
<< <br>
>> <br>
test <br>
<<test <br>
>> <br>
another test <br>
<<another test <br>
>> <br>
How can I solve this problem? If you have ANY advice you're welcome.