tags:

views:

76

answers:

4

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;
}

Thanks Rob

+2  A: 

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)?

Santiago Lezica
the end of the input should be a newline
robdavies35
Scan your buffer for newlines, then :)
Santiago Lezica
+1  A: 

Assuming that you only want to read a single line, then use LINE_MAX, which is defined in <limits.h>:

#include <stdio.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...
Steve Emmerson
LINE_MAX is NOT C89 or C99, its only compiler specific
A: 

here a concatenation solution:

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);
A: 

If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(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:

#include <stdio.h>
#include <string.h>

#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    char *big_buffer = new char[BIG_BUFFERSIZE];
    big_buffer[0] = '\0';
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
        {
            strcat(big_buffer, buffer);
        }
    }
    return 0;
}
jholl