user2989065
user2989065

Reputation: 13

What's wrong with my getNumber() function?

I'm making a program for class, if you run it and enter positive numbers, the purpose of the assignment is clear. However, it appears my int getNumber(); function isn't working correctly. The purpose of the function is to collect a single positive number and return it. Here's the code:

    int getNumber()
{
    int number;
    cin >> number;
    if (number < 0)
    {
        cout << endl; "Number cannot be negative: Please enter a nonnegative value: ";
        cin >> number;
    }
    else 
        return (number); 
}

If you need the rest of the program let me know. I call it as i = getNumber(); movies = new int[i];

EDIT: Sorry, I forgot to mention that the problem was it wouldn't print out the cout line, but would end the line correctly. Immediately after posting it I remembered that if-else was a condition clause and not a loop and switched it but still had the same problem. I didn't realize that it would still accept a negative number because I always ended the program once it failed to print the line "Number cannot be negative..." I put a ; instead of << after endl, but thanks for solving a problem I didn't know I would have. And sorry for not actually saying the problem the first time around.

Upvotes: 0

Views: 4502

Answers (3)

Josamoda
Josamoda

Reputation: 77

    int getNumber()
{
    int number;
    cin >> number;
    while(number<0) // A while loop will allow you to continually input numbers if the value is negative
    {
        cout << endl; "Number cannot be negative: Please enter a nonnegative value: ";
        cin >> number;
    }

        return number; // you don't need parenthesis before and after number
}

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67295

Your code only returns a value when the number is not negative. I'm assuming this is a compiler error.

Also, what happens if it's a negative number but the user enters a second negative number. You need something more like this:

int getNumber()
{
    int number;

    cin >> number;
    while (number < 0)
    {
        cout << endl; "Number cannot be negative: Please enter a nonnegative value: ";
        cin >> number;
    }
    return number;
}

Upvotes: 1

simonc
simonc

Reputation: 42185

Only one branch of your if condition returns a value. If the first number entered is negative, the function doesn't return anything.

Your compiler should have warned about this.

You probably want to replace your if with a while loop which executes repeatedly until an acceptable number is entered:

int getNumber()
{
    int number;
    cin >> number;
    while (number < 0)
    {
        cout << endl; "Number cannot be negative: Please enter a nonnegative value: ";
        cin >> number;
    }
    return number; 
}

Upvotes: 3

Related Questions