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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With