嗨,我正在尝试编写一个函数来处理用户的输入,允许他们输入“y”、“yeah”、“sure”、“absolute”等来回答“是或否”的问题。这是我的代码的一部分,编译没有错误,但不起作用。
void distinguish_string(char s[])
{
if (s[0] == 'y')
s = "yes";
else if (s[0] == 'n')
s = "no";
else
printf("Please eneter a valid answer. Like 'yes' or 'no', 'y' or 'n'.\n> ");
}
void play(Node **currentNode)
{
char answerOfQuestion[60];
........
fgets(answerOfQuestion, 60, stdin);
strtok(answerOfQuestion, "\n");
distinguish_string(answerOfQuestion);
.......
}
因为我稍后需要使用
if(strcmp(answerOfQuestion,"yes") == 0)
所以我的函数必须返回“yes”,而不是像 1 或 0 这样的 int。
有什么办法可以解决这个问题吗? 请帮忙
最佳答案
您必须将规范字符串复制到数组中(而不是仅仅修改函数中的本地指针所指向的内容):
void distinguish_string(char s[])
{
if (s[0] == 'y')
strcpy(s, "yes");
else if (s[0] == 'n')
strcpy(s, "no");
else
printf("Please enter a valid answer. Like 'yes' or 'no', 'y' or 'n'.\n> ");
}
但请注意,调用代码无法知道给出的答案是“确定”或“绝对”并执行任何操作,因为它不返回状态或任何内容。
这是一个不寻常的界面;大多数情况下,您不会像这样覆盖输入参数。然而,无论给出还是采取错误检测,它都没有错误。
关于C——编译没有错误但函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978130/