How to return string from a char function

2019-09-24 04:24发布

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

6条回答
Summer. ? 凉城
2楼-- · 2019-09-24 04:25

What does invalid should be mapped to? You should have a convention like this:

char invalid_category = '?';

or perhaps:

#define INVALID_CATEGORY '?'

This is better defined outside of the getCategory function so that the calling code can access it.

Also it isn't evident what your code returns when valid arguments are passed to it.

查看更多
Melony?
3楼-- · 2019-09-24 04:29

You're defining a variable named invalid. Its contents are undefined (it could be anything from -128 to 127). When you return this variable you're returning anything; do you want to assign something to the invalid variable before you return it? e.g.


char invalid;
invalid = 'i';
if ( ... ) {
  return invalid;
} else {
  return 0;
}
查看更多
Evening l夕情丶
4楼-- · 2019-09-24 04:30

you need to (very carefully) pore over your textbook to ascertain the multitude of errors in the above code.
1, your test in getCategory will almost certainly not do what you want it to do.
2, you ARE returning invalid in some cases (but not all, see #1). However, there is no way to know that as invalid has no known value.
3. in other cases, getCategory returns no value at all

查看更多
倾城 Initia
5楼-- · 2019-09-24 04:46

By the way, in your function getCategory, you have a variable that is not used nor declared - starvation. Where does that come from? I doubt that is a global variable.

Also, the variable bmirange does not make sense nor would it compile

bmirange=[weight/(height*height)];

as you can see that is a left hand side expression (LHS) but you have used an array subscript operators on the right hand side of expression (RHS). That is an illegal statement!

What was your intention there? Was that meant to be a pair of parenthesis?

Can you confirm this?

A lot of the answers are confusing because the OP did not make themselves clear on what is the error nor an explanation as to what is going on which is leading others to end up with code posted that does not satisfy the OP.

Hope this helps, Best regards, Tom.

查看更多
【Aperson】
6楼-- · 2019-09-24 04:48

The getCategory method doesn't always return (because of the if statement). Also, not sure about the height in if statement. Add another return invalid at the end of the method.

char getCategory(float height,float weight)
{
    char invalid;
    if(height<=0 || weight<=0)
       return invalid;
    return 0
}
查看更多
Deceive 欺骗
7楼-- · 2019-09-24 04:52

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.

查看更多
登录 后发表回答