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;
}
If you want to concatenate the input, then replace
printf("%s\n", buffer);
withstrcat(big_buffer, buffer);
. Also create and initialize the big buffer at the beginning:char *big_buffer = new char[BIG_BUFFERSIZE];
big_buffer[0] = '\0';
. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit:if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
. The modified program would look like this:here a concatenation solution:
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)?
Exits the loop if the line is empty(Improving code).
Exit when Enter is pressed.
Concatenation and dinamic allocation(linked list) to a single string.
Assuming that you only want to read a single line, then use
LINE_MAX
, which is defined in<limits.h>
: