Search code examples
cstdin

Read line from stdin until EOF and print the text after test for first character


I wanr interactive(I want to) read a line from standard input until EOF but after each line I want to print if the line first character is '+' then print "OK" else print "NOT OK". I tried this code but this prints "NOT OK" even if the line I input has a first character equal to '+'.

int main()
{
    #define BUF_SIZE 1024
    char buffer[BUF_SIZE];
    size_t contentSize = 1;
    /* Preallocate space.  We could just allocate one char here,
    but that wouldn't be efficient. */
    char *content = malloc(sizeof(char) * BUF_SIZE);
    if(content == NULL)
    {
        perror("Failed to allocate content");
        exit(1);
    }
    content[0] = '\0'; // make null-terminated
    while(fgets(buffer, BUF_SIZE, stdin))
    {
        char *old = content;
        contentSize += strlen(buffer);
        content = realloc(content, contentSize);
        if(content == NULL)
        {
            perror("Failed to reallocate content");
            free(old);
            exit(2);
        }
        strcat(content, buffer);
        if (content[0]== '+')  {
            printf("OK\n");
        } else {
            printf("NOT OK\n");
        }
    }

    if(ferror(stdin))
    {
        free(content);
        perror("Error reading from stdin.");
        exit(3);
    }
}

Solution

  • You are concatenating the buffer to the content

    strcat(content, buffer);
    

    So for the 1st input , suppose "abc" content will be abc and it will print NOT OK . For the 2nd input, suppose "+xyz" content will be abc+xyz so the value of content[0] will always be "a" and hence it will always print NOT OK.

    Similarly if your 1st input is "+abc" , then it will always print OK for all the inputs.

    Use strcpy instead of strcat

    strcpy(content, buffer);