如何从一个字符函数返回字符串 [英] How to return string from a char function

查看:134
本文介绍了如何从一个字符函数返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的功能的getCategory()返回无效,而不是打印单词无效(即,而不是用printf)时输入功能无效(iewhen无论是身高或体重较低接零) 。
请帮助:

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;焦炭的getCategory(浮点身高,体重浮动)
{
    字符无效='\\ 0';
    浮bmirange;    如果(高度< = 0 ||重量< = 0)
        返回无效;
    其他
    {
        身高=身高* 0.01; //1厘米=0.01米
        bmirange =体重/(身高×高)];        如果(bmirange< 15)
            返回饥饿;
    }
}诠释的main()
{
    字符类别;
    浮身高,体重;    的printf(请输入高度);
    scanf函数(%F,&安培;高度);    的printf(请输入权重);
    scanf函数(%F,&安培;重量);    类别=的getCategory(身高,体重);    如果(类别== 0)
        的printf(无效);
    其他
        的printf(%C类);
 }


解决方案

注:原来的问题已经改变了很多很多次,code已经改变了,就像常在每次迭代引入新的错误。在我离开这个答案,因为它回答了原来的code,看历史。下面这个回答有更新给予忠告,而不是code,因为这似乎更适合这里。

嗯,astander带走了他的答案。但也许这就是你应该实际上有:*

 字符的getCategory(浮点身高,体重浮动)
{
    字符无效='\\ 0';    如果(高度< = 0 ||重量< = 0)
        返回无效;    返回'C'; / *为有效的​​情况下做一些事情* /
}

* 最初包含高度问题||重量< = 0 和没有价值的变量无效

上的code注:结果
有了适当的缩进,你的程序流程变得更加清晰。我纠正你的if语句,假设这是你的打算,其实。最后一行应该包含你当前在你的问题排除在外。我加在第一行初始化,因为有一个值是更好然后没有一个值(这意味着:如果你没有初始化,它可以是任何东西,真的)。

在您的电话code,你可以这样做:

 类别=的getCategory(身高,体重);
如果(类别== 0)
    的printf(无效);
其他
    的printf(%C类);

这实际上打印字无效的输出,如果这是你的打算。


更新:基于问题的新案文,认为提问者想要别的东西,所以这里是一个新的答案很清楚。我离开上面,它仍然与原来的问题,有效的。

您现在正在询问的的打印字无效和的的使用特殊的值无效的情况下。相反,你问回无效,我的理解与值返回字符串无效(这本身考虑,仍然是返回一个特殊值)

你不能做到这一点

简而言之:你不能这样做。目前的函数的返回类型字符。我不知道你的函数的目的,但我敢肯定,你给它一些思考,并有一个理由使用字符。一个char只能包含一个字符。和单词无效的,是多个字符。你有几个选项,选择哪个最适合你:

其他方式


  • 改变返回类型为字符串而不是字符的,这需要所有参与code的重新设计

  • 与返回的一个特殊值定居。你不显示你的函数体,但如果它通常不会返回 \\ 0 ,您可以使用该值,如我上面的例子。当然,你可以选择任何其他字符值;

  • 抛出一个异常,并在正文中使用一个try / catch。但是你用C,而不是C ++。下面是描述了使用C ++链接 - 风格的异常处理对于C ,但是这可能是一个位外的界限,学习C可以更好地采取在当时的一小步。

什么是常用最佳实践

在正常情况下,这是常见的选择任何一种特殊情况下的值或异常(典型的如C ++,Java和Python的更结构化的语言)(如C或汇编旧的或更基本的语言典型值)。它通常被认为不好的做法,改变的特殊情况为目的的完整功能(如输入无效)。

为什么

相反,该函数的调用者应该处理这些特殊情况。这样做的原因是编程一个非常重要的规则:该函数可以永远不知道该功能的用户想要做的,当坏事发生(非法输入)事先什么。人们可以选择打印非法输入(对命令行用户),另一个想(在库)退出程序,并又一想忽略,什么也不做(用于自动处理)。总之:你想达到什么样的,你应该尝试不同的实现(见2选项及以上3,和我原来的解决方案)

教师和教科书

使用这种方法是迄今为止最容易,也最好理解为任何(未来)同工,因为它遵循通用计算机的做法。当然,我还没有看到你的作业或教科书,所以我不能在他们想要的东西方向的解决方案出来,而且也不会是第一本教科书或教师先告诉你走错了路,让你颤抖,然后告诉你正确的路径。

I want the function getCategory() to return "invalid" , instead of printing the word "invalid" (i.e instead of using printf ) when input to the function is invalid (i.e.when either height or weight are lower then zero). please help:

#include<stdio.h>
#include<conio.h>

char getCategory(float height,float weight)
{
    char invalid = '\0'; 
    float bmirange;

    if(height<=0 || weight<=0)
        return invalid;
    else
    {
        height=height*0.01;        //1 centimeter = 0.01 meters
        bmirange=[weight/(height*height)];

        if(bmirange< 15 )
            return starvation;
    } 
}

int main()
{
    char Category;
    float height,weight;

    printf("enter height");
    scanf("%f",&height);

    printf("enter weight");
    scanf("%f",&weight);

    Category=getCategory(height,weight);

    if(Category == 0)
        printf("invalid");
    else
        printf("%c", Category);
 }

解决方案

NOTE: the original question has been altered many, many times and the code has changed just as often, introducing new errors in each iteration. I leave this answer as it answered the original code, see history. Below this answer there's an update giving advice instead of code, as that seems more appropriate here.

Hmm, astander removed his answer. But perhaps this is what you should actually have:*

char getCategory(float height,float weight)
{
    char invalid = '\0';

    if(height<=0 || weight<=0)
        return invalid;

    return 'c';   /* do something for the valid cases */
}

* originally the question contained height || weight <= 0 and no value for variable invalid.

Notes on the code:
With proper indentation, your program flow becomes clearer. I corrected your if-statement, assuming this was your intend, actually. The last line should contain what you currently left out in your question. I added an initialization in the first line, because having a value is better then not having a value (which means: if you don't initialize, it can be anything, really).

In your calling code, you can do this:

Category = getCategory(height, weight);
if(Category == 0)
    printf("invalid");
else
    printf("%c", Category);

which actually prints the word "invalid" to the output, if that was your intend.


Update: based on new text in the question, it's clear that the asker wants something else, so here's a new answer. I leave the above, it's still valid with the original question.

You're now asking not to print the word "invalid" and not to use a special value for the invalid case. Instead, you ask to return "invalid", which I understand as returning the string with the value "invalid" (which, taken in itself, is still returning a special value).

You cannot do it

In short: you cannot do that. The current function has return type char. I don't know the purpose of your function, but I'm sure you've given it some thought and there's a reason for using a char. A char can only contain one character. And the word "invalid" is multiple characters. You have a few options, choose whichever suits you best:

Other ways

  • change the return type to be string instead of char, this requires redesign of all code involved;
  • settle with returning a special value. You don't show the body of your function, but if it would normally never return \0, you can use that value, as in my example above. Of course, you can choose any other char value;
  • raise an exception and use a try/catch in the body. But you use C, not C++. Here's a link that describes using C++-style exception handling for C, but this may be a bit out-of-bounds, learning C can better be taken on a small step at the time.

What's commonly best practice

In normal situations, it is common to choose either special-case values (typical in older or more basic languages like C or assembler) or exceptions (typical for more structured languages like C++, Java, Python). It's commonly considered bad practice to change a complete function for the purpose of special-cases (like invalid input).

Why

Instead, the caller of the function should deal with these special cases. The reason for this is a very important rule in programming: the function can never know beforehand what users of that function want to do when something bad happens (illegal input). One may choose to print "Illegal input" (for commandline users), another wants to quit the program (for in a library) and yet another wants to ignore and do nothing (for automatic processing). In short: what you are trying to achieve, you should try to achieve differently (see option 2 and 3 above, and my original solution).

Teachers and textbooks

Using this approach is by far the easiest and also best to understand for any (future) co-workers as it follows common computer practices. Of course, I haven't seen your assignment or textbook, so I can't tell in what direction they want a solution, and it won't be the first textbook or teacher to first show you the wrong path, let you tremble, and then show you the right path.

这篇关于如何从一个字符函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆