pandora
pandora

Reputation: 21

Ignoring leading newline("\n") in c

I am currently working on an practice. My program is working and I just want to make it more robust and foolproof. The code is of the following:

printf("Enter Name : ");
memset(userinput, '\0', 50);
fgets(userinput, 50, stdin);

I accidentally hit the enter key(newline) and for my program, the system just dangle there and couldn't accept anymore inputs. I am only allowed to use fgets. So is there any way of rejecting \n from being entered as a field?

Upvotes: 2

Views: 134

Answers (2)

chux
chux

Reputation: 153338

So is there any way of rejecting \n from being entered as a field?
... to make it more robust and foolproof.

Code should not prevent '\n' from being read via fgets(). Instead, code should assess that input for validity. A leading '\n' is likely only 1 concern. Make code easy to update as certainly the criteria for a valid name will evolve.

I recommend a separate name test.

bool ValidNameInputTest(const char *userinput) {
  if (*userinput == '\n') return false; // fail
  // add other tests as needed
  return true;
}

In a loop, test and repeat as needed. Code should exit the loop on success. When an end-of-file or input error occurs, code should detect/handle that too.

...
char userinput[50];

do {
  printf("Enter Name : ");
  fflush(stdout);   // add to insure above output is seen before reading input
  //memset(userinput, '\0', 50);// Commented out as not needed - although useful for debug

  // Check return value and used a derived size
  //fgets(userinput, 50, stdin);
  if (fgets(userinput, sizeof userinput, stdin) == NULL) {
    Handle_EndOfFile_or_Error();
  }
} while (!ValidNameInputTest(userinput));

Upvotes: 0

rollstuhlfahrer
rollstuhlfahrer

Reputation: 4078

One way you could do it is to check if the first character is a newline:

do {
    printf("Enter Name : ");
    memset(userinput, '\0', 50);
    fgets(userinput, 50, stdin);
}
while ( userinput[0] == '\n'); 

printf("Hello %s", userinput);

This would still leave you up to space + newline, but its a first start.

Upvotes: 3

Related Questions