c - 如何通过简单地按 Enter 键使用 scanf 来接受默认值?

标签 c objective-c

我想知道是否有人可以帮我解决这个问题:

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

是否可以让用户简单地按 Enter 键并接受默认设置(在本例中为:/mnt/Projects)? 目前,如果用户按下 Enter,光标只是转到下一行,仍然需要输入。

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

谢谢!

最佳答案

不,scanf() 不能配置为接受默认值。为了让事情变得更有趣,scanf() 不能接受空字符串作为有效输入; “%s”转换说明符告诉 scanf() 忽略前导空格,因此它不会返回,直到您键入非空格的内容并然后按 Enter 或返回。

要接受空输入,您必须使用类似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)
  }
}

编辑

default 更改为 defaultPath;忘记了 default 是保留字。 代码猴子,没有香蕉!

关于c - 如何通过简单地按 Enter 键使用 scanf 来接受默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2311156/

相关文章:

c++ - 在 Linux/Unix 中同时使用 2 个程序访问 stdin

objective-c - 如何继承 UITableViewCell 的子类?

objective-c - 私有(private)接口(interface)与私有(private)方法 - objective-c

ios - 如何获取适合特定矩形的 NSAttributedString 子字符串?

自动计算批处理价格

c - 如何抑制 C 中的 openssl 错误输出?

c - 在夹板的帮助下消除代码中的安全缺陷

android - 如何在 android cmake 项目中包含 <glib.h>

ios - NsNumberFormatter 没有给出正确的结果

ios - 当文本字段开始编辑时停止 UITableView 滚动