user3475815
user3475815

Reputation: 11

Reading input with fgets?

I am trying to get the input of one character using fgets(). To my knowledge fgets will addend the \n to the end of the input unless there is no room.

char test[1];
fgets(test,1,stdin);
readRestOfLine();
while (strcmp(test,"z") != 0){
......
......
}

Anyway the loop is never run even when z is entered. Why is this?

Upvotes: 0

Views: 567

Answers (3)

Armali
Armali

Reputation: 19375

man fgets

char *fgets(char *s, int size, FILE *stream);

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s... A terminating null byte ('\0') is stored after the last character in the buffer.

In your case of size 1 this means fgets() reads in zero, i. e. no, characters and stores the terminating '\0' in test[0].

Upvotes: 2

Jabberwocky
Jabberwocky

Reputation: 50778

As you stated correctly fgets appends a '\n' at the end of the string. So if you input just "z", then the resulting string will be "z\n" which is not equal to "z".

Furthermore the size of the buffer for fgets is only on character long in your program, but this length must be at least as long as your longest string you intend to enter.

Try this:

char test[100];   // space for 98 characters + \n + terminating zéro
fgets(test, 100, stdin);
readRestOfLine();
while (strcmp(test,"z\n") != 0){
   ......
   ......
}

Upvotes: 0

Dabo
Dabo

Reputation: 2373

strcmp operates on strings as follows from it's name, so test has to be \0 terminated string. test must have room for \0.

Upvotes: 0

Related Questions