只需按Enter键,如何使用scanf接受默认值?

Ria*_*iaz 4 c objective-c

我想知道是否有人可以帮助我:

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

是否可以允许用户仅按Enter键并接受默认值(在这种情况下为/ mnt / Projects)?目前,如果用户按下Enter键,则光标仅移至下一行,仍然需要输入。

我得到的印象scanf不允许这样做,在这种情况下,我应该使用什么?

谢谢!

Joh*_*ode 6

否,scanf()无法配置为接受默认值。为了使事情变得更加有趣,scanf()不能接受空字符串作为有效输入。“%s”转换说明符告诉scanf()您忽略前导空格,因此,除非您键入非空格,然后按Enter或Return ,否则它不会返回。

要接受空输入,您必须使用fgets()。例:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

更改defaultdefaultPath; 忘记那default是保留字。 错误的代码猴子,没有香蕉!