C Programming: How to make program end when user inputs a newline

Viewed 792

I am building a basic C program that continuously asks users for a string input and prints out the entered input. The program is supposed to exit when a user enters a blank line. However, in my following program, even when I have a conditional that checks whether the user entered a blank line, the program still keeps on going until the user types an input. Below is my code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char userString[100];
    while (1 == 1) {
        scanf("%s", userString);
        printf("USER ENTERED %s\n", userString);
        if (userString[0] == '\n') {
            exit(0);
        }
    }
}
2 Answers
    scanf("%s", userString);        scanf("%s", userString);

scanf with %s will read the input stream until it meets any of the whitespace. Thus newline will not be included as part of userString.

Use fgets instead.

   fgets(userString, sizeof userString, stdin);

The scanf function usually read space delimited "token" (words, numbers, etc.).

Almost all format specifiers (including %s) skip leading white-space (all spaces, such as normal space, tab and newline). The only two formats that doesn't skip space is the %[ format and the %c format, the first of which could be useful for you but I recommend against it.

To read lines I recommend the fgets function instead. If the only character in the buffer is the newline then you have an empty line.

Related