简体   繁体   中英

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?

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, ie no, characters and stores the terminating '\\0' in test[0] .

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

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){
   ......
   ......
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM