Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An extra blank line before the program terminates

Tags:

c

I'm really new to programming and just wanted to ask a quick question. So I made this program that reads off whatever the user inputs, then output the exact same thing until the user presses enter without any input.

int main(void) {
    char s1[30];

    while (s1[0] != NULL) {
        gets(s1);
        printf("%s\n", s1);
    }
    system("PAUSE");
    return 0;
}

Then I realized that when I press enter to end the program, the program creates an extra blank line before the program terminates.

So I changed my code as it is below

int main(void) {
    char s1[30];

    while (1) {
        gets(s1);
        if (s1[0] == NULL)
            break;
        printf("%s\n", s1);
    }
    system("pause");
    return 0;
}

And now the program terminates without creating an extra blank line. But I really can't seem to figure out the factors that made the difference between two codes.

Any help would be appreciated. Thanks!

like image 779
Tuto Avatar asked Jul 08 '26 05:07

Tuto


1 Answers

As already told in the comment section don't use gets it is dangerous(why-is-the-gets-function-so-dangerous-that-it-should-not-be-used).

And replace gets with fgets as below.

while (fgets(s1,sizeof s1,stdin)) {
    if (s1[0] == '\n') //fgets() reads the newline into the buffer
     break;
     printf("%s", s1); // Don't need to append \n to print as s1 will be having \n already.
}

To answer your question

gets(s1);
if (s1[0] == NULL) // Not valid comparison use \0 instead of NULL

When you press enter to terminate the program, gets will not read the newline(\n) character into the buffer hence your s1 will be untouched by gets and will have indeterminate values(seemingly it is having 0's in your case) so you are hitting if (s1[0] == NULL) and breaking out of the loop without printing newline.

like image 154
kiran Biradar Avatar answered Jul 10 '26 00:07

kiran Biradar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!