Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

printf("Enter path for mount drive (/mnt/Projects) 
");
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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...