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, '
');
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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…