[英]C -- compile without error but function not working
嗨,我正在尝试编写一个函数来处理用户的输入,以允许他们输入“y”、“是”、“确定”、“绝对”等来回答“是或否”问题。 这是我的代码的一部分,编译没有错误但不起作用。
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)
所以我的函数必须返回“是”而不是像 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> ");
}
但是请注意,调用代码无法知道给出的答案是“确定”还是“绝对”,并且无法对此做任何事情,因为它不返回状态或任何内容。
这是一个不寻常的界面; 大多数情况下,您不会像那样覆盖输入参数。 但是,给出或接受错误检测,它没有错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.