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

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

问题描述

我想要函数getCategory()返回invalid,而不是打印单词invalid(即,而不是使用printf)当输入到函数无效(iewhen的高度或重量低于零) 。
请帮助:

 #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厘米= 0.01米
bmirange = [重量/(身高*身高)];

if(bmirange< 15)
return starvation;
}
}

int main()
{
char类别;
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);
}


解决方案

注意:原始问题已更改多次,许多次,代码已经更改频繁,在每次迭代中引入新错误。我离开这个答案,因为它回答原来的代码,见历史。下面这个答案有一个更新给建议,而不是代码,因为这似乎更适合这里。



但是,astander删除了他的答案。但也许这是你实际应该有的:*

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

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

return'c'; / *为有效的情况执行某些操作* /
}

* 最初的问题包含 height ||重量<= 0 并且没有值无效



代码注释

通过适当缩进,程序流程变得更加清晰。我纠正了你的if语句,假设这是你的意图,实际上。最后一行应该包含您当前在您的问题中遗漏的内容。我在第一行添加了一个初始化,因为有一个值比没有值更好(这意味着:如果你不初始化,它可以是任何东西,真的)。



在您的呼叫代码中,您可以这样做:

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

其实输出了invalid >




更新:根据问题中的新文字,否则,这里有一个新的答案。



您现在要求不要打印无效和为无效的情况使用特殊值。相反,你要求返回invalid,我理解为返回值为invalid的字符串(其本身仍然返回一个特殊值) 。



你不能这样做。



总之:你不能这样做。当前函数具有返回类型 char 。我不知道你的函数的目的,但我相信你给了一些想法,有一个使用 char 的原因。 char只能包含一个字符。而无效一词是多个字符。您有几个选项,请选择最适合您的选项:



其他方式




  • string 改为 char ,这需要重新设计涉及的所有代码;

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

  • 引发异常并在正文中使用try / catch。但是你使用C,而不是C ++。这里有一个链接,描述了对C 使用C ++风格的异常处理,但这可能是



通常最好的做法是, / h3>

在正常情况下,通常选择特殊情况值(通常用于较老或较基本的语言,如C或汇编程序)或异常(典型的更多结构化语言C ++,Java,Python)。通常认为为特殊情况(如无效输入)更改完整函数是不好的做法。



为什么



相反,函数的调用者应该处理这些特殊情况。其原因是编程中非常重要的规则:当发生错误(非法输入)时,函数不能预先知道该函数的用户想要做什么。可以选择打印非法输入(对于命令行用户),另一个要退出程序(在库中),另一个想忽略并不做任何操作(自动处理)。总之:你想达到的目的,你应该尝试不同的方式(见上面的选项2和3,和我原来的解决方案)。



教师和教科书< h3>

对于任何(未来的)同事来说,使用这种方法是最简单也最好的,因为它遵循常见的计算机实践。当然,我没有看到你的作业或教科书,所以我不能告诉他们想要一个解决方案的方向,它不会是第一本教师或老师,首先告诉你错误的道路,让你颤抖,然后向您显示正确的路径。


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.

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

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