在Visual Studio 2015社区版上运行
实际上,我正在修改c ++的概念,其中在调用函数时遇到错误。例如:
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;
}
它要求用户根据
NO_OF_TURN
进行猜测。但是,当在函数/方法GetGuessAndPrintBack()
中定义for循环时,例如: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;
}
它只要求猜测一次。
最佳答案
它只询问一次,因为您在for循环中有return Guess
语句。在for循环的第一次迭代中,将执行return语句,并终止GetGuessAndPrintBack()
函数。return Guess
语句应位于for循环语句之外。
关于c++ - 了解for循环和函数c++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43322879/