【发布时间】:2015-12-12 00:05:35
【问题描述】:
我正在编写一个名为 GetPattern() 的函数,它将在我的 main() 函数中使用。
这是我的main() 如何使用GetPattern() 函数的上下文。
int main(void)
{
int attempt=0, option=-1;
char pattern[SIZE+1], replacement[SIZE+1];
char name[20];
FILE *in, *out;
printf("Enter the pattern to find:");
GetPattern(pattern);
out = CreateFile();
Find(in, pattern, out);
fclose(in);
fclose(out);
return 0;
}
这是我的GetPattern() 函数:
void GetPattern(char *tmp)
{
// prompt the user for the pattern to be found/replaced
// note: any character, including ' ', maybe be part of the pattern
// we assume that the pattern has no more than 20 characters. If the user
// enters more than 20 characters, only the first 20 will be used.
int i;
for (i = 0; i < 20; i++) // iterate 20 times
{
scanf(" %c", &tmp[i]);
if (tmp[i] == '\n') // if user hits enter, break the loop
{
tmp[i] = '\0'; // insert '\0' at the end of the array
break;
}
else
tmp[i+1] = '\0'; // insert '\0' at the end of the array
}
printf("%s\n", tmp); // see what's in tmp[]
return;
}
GetPattern() 函数自己工作;与main() 函数分开,但是当我将它放入main 时,它只接受20 个字符并且不少于。即使我按下 ENTER(即 '\n'),循环也不会中断——它会继续进行。
你觉得这段代码有什么明显的错误吗?
【问题讨论】:
-
" %c"中的空格表示“跳过空格”。这包括换行符。所以tmp[i]永远不会是'\n'。 -
呃。你一定是在开玩笑吧。这种语言没有胜利。谢谢@user3386109。
-
当用户单独点击
[Enter]时,scanf 没有字符可供读取,因此不会发生转换。无论[Enter]被按下多少次,scanf都高兴地坐在那里等待一个角色。输入结束标记为[ctrl+d](Windows 上为[ctrl+z])。 -
好吧,不要通过单个半标准函数的行为来判断 C,语言。我已经用 C 语言编程了 30 多年,而且我从未 [不是一次] 使用过 scanf 等。人。我一直使用 fgets、fgetc、strtok、strtol、atoi 等来代替。为什么?好吧,这只是我的看法,但当我第一次看到 scanf 时,我的看法是它是恶性的 :-)。而且,我觉得通过 不 使用 scanf 可以更好地处理更一般的情况。但是,其他人成功地使用它--YMMV
-
scanf()系列函数具有许多必须全部考虑在内的功能。建议使用:`fgets(tmp, 20, stdin);因为该单个命令将处理您想要做的所有事情。但是,强烈建议不要使用“神奇”数字(如 20),而是使用 #define 为该数字赋予有意义的名称,然后在整个代码中使用该有意义的名称。