I've written the following code to read a line from a terminal window, the problem is the code gets stuck in an infinite loop. The line/sentence is of undefined length, therefore I plan to read it in parts into the buffer, then concatenate it to another string which can be extended via realloc
accordingly. Please can somebody spot my mistake or suggest a better way of achieving this?
#include <stdio.h> #include <string.h> #define BUFFERSIZE 10 int main (int argc, char *argv[]) { char buffer[BUFFERSIZE]; printf("Enter a message: \n"); while(fgets(buffer, BUFFERSIZE , stdin) != NULL) { printf("%s\n", buffer); } return 0; }
The function fgets() reads the characters till the given number from STDIN stream.
The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n -1, whichever comes first.
C library function - fgets() The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
Even though both the functions, gets() and fgets() can be used for reading string inputs. The biggest difference between the two is the fact that the latter allows the user to specify the buffer size. Hence it is highly recommended over the gets() function.
here a concatenation solution:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFERSIZE 10 int main() { char *text = calloc(1,1), buffer[BUFFERSIZE]; printf("Enter a message: \n"); while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */ { text = realloc( text, strlen(text)+1+strlen(buffer) ); if( !text ) ... /* error handling */ strcat( text, buffer ); /* note a '\n' is appended here everytime */ printf("%s\n", buffer); } printf("\ntext:\n%s",text); return 0; }
You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.
How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With