简体   繁体   中英

C -- compile without error but function not working

Hi I am trying to write a function to handle inputs by users for allowing them to enter "y", "yeah", "sure", "absolutely" and so on to answer "yes or no" question. Here is part of my code, compile without errors but is not working.

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);
    .......
}

Since I need to later use

if(strcmp(answerOfQuestion,"yes") == 0)

So my function must return "yes" instead of int like 1 or 0.

Any way to solve this? Please help

You have to copy the canonical string into the array (instead of just modifying what the local pointer in the function points at):

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> ");
}

Note, though, that the calling code has no way of knowing that the answer given was 'sure' or 'absolutely' and doing anything about it because it doesn't return a status or anything.

This is an unusual interface; most often you don't go overwriting an input argument like that. However, give or take the error detection, it is not wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM