3

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!

Mike
  • 4,041
  • 6
  • 20
  • 37
Tuto
  • 114
  • 6
  • 4
    Don't use `gets`. Never *ever* use `gets`! It's a [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) function that have even been removed from the C standard. Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead. – Some programmer dude Oct 18 '18 at 11:09
  • 4
    `gets` is not valid C. `s1[0] == NULL` is not valid C. Burn your book/teacher with fire and get a new one. – Lundin Oct 18 '18 at 11:09
  • 3
    Also note that `NULL` is for null *pointers*, not the string null terminator (which is `'\0'`). And uninitialized local variables (including arrays like `s1`) will really be uninitialized, and have *indeterminate* (and seemingly random) values. – Some programmer dude Oct 18 '18 at 11:10

1 Answers1

1

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.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44