Consider my following code:
int main() {
int letter_count=4;
char tempstring[6];
char userStrings[4][4];
for(int i=0;i<4;i++){
fgets(tempstring,letter_count+1,stdin);
tempstring[strcspn(tempstring, "n")] = 0;
strcpy(userStrings[i],tempstring);
printf("n%s found from %dn",userStrings[i],i);
}
return 0;
}
Now, what I am trying to do is: I want the user to input 4 words. Here, fgets()
caputures these inputs. So, whenever, I try to input something smaller than 4 words, say foo
and press enter the output is:
foo found from 0
But, whenever, I enter something of 4 words or more than that, it becomes unexpected. Consider, I input foil and press enter, this is what happens:
foil found from 0
found from 1
Why is there a line found from 1
. The string tempstring
has somewhat received a whitespace from the user input and the loop has advanced by one step, which should not have been the case. What I anticipate is, since fgets()
receives more than five characters from user, it advances the loop once. Is there any way, I just want fgets()
to receive exactly four letters or less and let the loop run only once?
I may try scanf()
and gets()
, but they cannot limit the size of user input. Any suggestions would gladly help me. Thanks.