SimpliCty
SimpliCty

Reputation: 35

C string disappears along with newline

I'm new to C and stackoverflow, so pardon me if my question is silly or a duplicate.

So i tried to read some lines of string (and integers) from a .txt files and store it into an array of tuples. The strings read from the file seems to contain '\n' everytime, so i use strcspn() to remove it.

    FILE* f = fopen("board.txt","r");
    int x;
    size_t size = 30;
    char *buffer;
    for (i=1;i<=32;i++)
        {
            buffer = (char *)malloc(size);
            x = getline(&buffer,&size,f);
            buffer[strcspn(buffer,"\n")] = 0;
            A[i].name = buffer;
            buffer = (char *)malloc(size);
            x = getline(&buffer,&size,f);
            buffer[strcspn(buffer,"\n")] = 0;
            A[i].type = buffer;
            buffer = (char *)malloc(size);
            x = getline(&buffer,&size,f);
            A[i].price = atoi(buffer);
        }
    for (i=1;i<=32;i++)
        printf("%s ",A[i].name);
    for (i=1;i<=32;i++)
        printf("%s ",A[i].type);

However, when i tried the code above, the printf failed to print anything. But then when i tried to use \n in the printf ( printf("%s\n",A[i].type); ) it worked just fine. It seems like the strings completely disappear when i remove the "\n", and then come back only when i put '\n' as i print it.

Can someone explain what is wrong in the code? Or is it a library problem? Thank you in advance.

Edit : So to explain it a little further, i need those string (name and type) to be printed into 'boxes' to form a kind of board game, so i think bringing newline would cause a lot of trouble later on.

Upvotes: 2

Views: 703

Answers (2)

jarr
jarr

Reputation: 102

printf belongs to the Standard I/O library, it is a line buffered function. So when this function is called, it stores characters in a buffer and the only way to get the output (to stdout) is to flush with a newline character. This is the way it was designed so as to maintain a minimal number of system calls as possible.

Try eliminating this,

 buffer[strcspn(buffer,"\n")] = 0;

Upvotes: 0

TheoretiCAL
TheoretiCAL

Reputation: 20581

This is the correct behavior. The '\n' causes the OS to flush the buffer used for prints, so that it appears on stdout. Without a '\n' the OS isn't forced to write your print to stdout yet.

Upvotes: 2

Related Questions