lifehack
lifehack

Reputation: 27

Understanding of for loop and function c++

Running on Visual Studio 2015 Community edition

Actually i am revising the concept of c++ in which i came accross an error while calling a function. For example:

string GetGuessAndPrintBack() {

    string Guess = "";
    cout << "Enter your Guess Here ";
    getline(cin, Guess);    //taking input from user
    cout << "Your Guess is " << Guess << endl;    //repeating back the user input
    return Guess;
}


int main()
{
    constexpr int NO_OF_TURN = 5;
    for (int i = 0; i < NO_OF_TURN; i++) {
        GetGuessAndPrintBack();
        cout << endl;
    }
    return 0;
}

It asks the user to guess according to NO_OF_TURN. But when the for-loop is defined in the function/Method GetGuessAndPrintBack() such as:

string GetGuessAndPrintBack() 
{
    constexpr int NO_OF_TURN = 5;
    for (int i = 0; i < NO_OF_TURN; i++) {
        string Guess = "";
        cout << "Enter your Guess Here ";
        getline(cin, Guess);      //taking input from user
        cout << "Your Guess is " << Guess << endl;       //repeating back the user input
        return Guess;
    }
}

int main()
{
    GetGuessAndPrintBack();
    cout << endl;
    return 0;
}

It asks for the guess only one time.

Upvotes: -1

Views: 93

Answers (3)

Nizar Ahmed
Nizar Ahmed

Reputation: 180

Remove return Guess from inside the loop to the end of the method

Upvotes: 1

BusyProgrammer
BusyProgrammer

Reputation: 2781

It asks for the guess only once because you have the return Guess statement inside the for loop. At the first iteration of the for-loop, the return statement is executed and the GetGuessAndPrintBack() function is terminated.

The return Guess statement should be outside the for-loop statement.

Upvotes: 1

SPlatten
SPlatten

Reputation: 5762

Because you have a return inside the loop which terminates the loop.

Upvotes: 1

Related Questions