返回函数中的字符

时间:2014-09-24 16:45:01

标签: c

#include <stdio.h>

char printBrowse(char choice);

int main(void) {
    char letter;
    printBrowse(letter);
    printf("-->%c", letter);
    getch();
}

char printBrowse(char choice) {
    printf("Welcome to Orange Movie Box\n\n");
    printf(" a)Browse by Name\n");
    printf(" b)Browse by Genre\n");
    printf(" c)Browse by Year\n");
    printf(" d)Browse by Age Rating\n");
    printf("Please choose your browsing method:");
    scanf("%c", &choice);

    return choice;
}

如何将printBrowse选择返回main?当我尝试运行此代码时,它可以工作,但是当我打印变量'letter'时,当我在printBrowse上输入时,它会打印'u'而不是'c'。

3 个答案:

答案 0 :(得分:4)

您可以使用返回值:

#include <stdio.h>

char printBrowse()
{
   char choice;
   printf("Welcome to Orange Movie Box\n\n");
   printf(" a)Browse by Name\n");
   printf(" b)Browse by Genre\n");
   printf(" c)Browse by Year\n");
   printf(" d)Browse by Age Rating\n");
   printf("Please choose your browsing method:");
   scanf("%c", &choice);
   return choice;
}

int main(void)
{
   char letter = printBrowse();
   printf("-->%c", letter);
   getch();
}

或者您可以通过指针传递char:

#include <stdio.h>

void printBrowse(char* choice)
{
   printf("Welcome to Orange Movie Box\n\n");
   printf(" a)Browse by Name\n");
   printf(" b)Browse by Genre\n");
   printf(" c)Browse by Year\n");
   printf(" d)Browse by Age Rating\n");
   printf("Please choose your browsing method:");
   scanf("%c", choice);
}

int main(void)
{
   char letter;
   printBrowse(&letter);
   printf("-->%c", letter);
   getch();
}

答案 1 :(得分:3)

这是因为当您从main()调用函数时,您不会将返回值存储在main()函数中的任何位置。

int main(void)
{
    char letter;
    letter = printBrowse(); //storing the return value of printBrowse() function in letter variable
    printf("-->%c", letter);
    getch();
}

同时你可以删除从函数printBrowse()

传递的参数
char printBrowse() {
    char choice;
    printf("Welcome to Orange Movie Box\n\n");
    printf(" a)Browse by Name\n");
    printf(" b)Browse by Genre\n");
    printf(" c)Browse by Year\n");
    printf(" d)Browse by Age Rating\n");
    printf("Please choose your browsing method:");
    scanf("%c", &choice);

    return choice;
}

答案 2 :(得分:1)

鉴于函数签名,我相信你想将printBrowse函数更改为: 除非传递变量&amp; letter的地址,否则将函数printBrowse传递给变量名称字母不会更改变量字母本身。

void printBrowse(char *choice)            //you pass the address of a char variable
{

  printf("Welcome to Orange Movie Box\n\n");
  printf(" a)Browse by Name\n");
  printf(" b)Browse by Genre\n");
  printf(" c)Browse by Year\n");
  printf(" d)Browse by Age Rating\n");
  printf("Please choose your browsing method:");
  scanf("%c", choice);

 }

相应地,您的主要功能需要进行一些更改:

int main(void)
{
  char letter;
  printBrowse(&letter);
  printf("-->%c", letter);
  //getch();   sorry, I don't understand why you need getch() here.
}