我想知道是否有人可以帮我解决这个问题:
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/