Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use scanf to accept a default value by simply pressing Enter key?

Tags:

c

objective-c

I was wondering if someone could please help me with this:

printf("Enter path for mount drive (/mnt/Projects) \n");
scanf("%s", &cMountDrivePath);  

Is it possible to allow the user to simply press Enter and accept the default (in this case: /mnt/Projects)? At present, if the user presses Enter, the cursor simply goes to the next line and input is still required.

I get the impression scanf does not allow this, in which case, what should I use?

Thanks!

like image 963
Riaz Avatar asked Dec 17 '22 02:12

Riaz


1 Answers

No, scanf() cannot be configured to accept a default value. To make things even more fun, scanf() cannot accept an empty string as valid input; the "%s" conversion specifier tells scanf() to ignore leading whitespace, so it won't return until you type something that isn't whitespace and then hit Enter or Return.

To accept empty input, you'll have to use something like fgets(). Example:

char *defaultPath = "/mnt/Projects";
...
printf("Enter path for mount drive (%s): ", defaultPath);
fflush(stdout);

/**
 * The following assumes that cMountDrivePath is an
 * array of char in the current scope (i.e., declared as
 * char cMountDrivePath[SIZE], not char *cMountDrivePath)
 */
if (fgets(cMountDrivePath, sizeof cMountDrivePath, stdin) != NULL)
{
  /**
   * Find the newline and, if present, zero it out
   */
  char *newline = strchr(cMountDrivePath, '\n');
  if (newline)
    *newline = 0;

  if (strlen(cMountDrivePath) == 0) // input was empty
  {
    strcpy(cMountDrivePath, defaultPath)
  }
}

EDIT

Changed default to defaultPath; forgot that default is a reserved word. Bad code monkey, no banana!

like image 129
John Bode Avatar answered Feb 28 '23 08:02

John Bode