它的功能过于复杂。只需在值不好时循环,并提示输入新值:
int GetMark(int ModuleIndex) { while (ModuleIndex < 0 || ModuleIndex > 100) { std::cout << "Invalid value.\n" std::cin >> ModuleIndex; } return ModuleIndex; }
递归在理论分析中非常方便,但在实践中它几乎总是一个错误。
您定义的方式的组合 GetMark 而你使用它的方式是有缺陷的。
GetMark
无论你做什么 GetMark ,输入的值 main 不会改变。
main
更改 GetMark 至:
int GetMark() { std::cout << "enter mark (0 - 100): " << std::endl; int mark; while ( std::cin >> mark ) { if ( mark >= 0 && mark <= 100) { return mark; } std::cout << "Invalid value " << mark << std::endl; std::cout << "enter mark (0 - 100): " << std::endl; } // Unable to read. // Throw exception, or exit with an error message. }
并改变其用途。代替
cout << "enter mark (0 - 100): " << endl; cin >> marks[i]; GetMark(marks[i]);
使用
marks[i] = GetMark();
一个工作版本 GetMark :
int GetMark() { std::cout << "enter mark (0 - 100): " << std::endl; std::string line; while ( getline(std::cin, line) ) { std::istringstream str(line); int mark; if ( str >> mark ) { if ( mark >= 0 && mark <= 100) { return mark; } } std::cout << "Invalid input: " << line << std::endl; std::cout << "enter mark (0 - 100): " << std::endl; } // Unable to read. // Throw exception, or exit with an error message. return 0; }
现场演示 。
基本上你需要做的是从这个方法中删除递归,只需依赖while循环。您需要使用失败的输入再次提示输入,然后再次测试该值以逃避循环,而不是调用该函数。
int GetMark(int ModuleIndex) //user input function { bool help; if (ModuleIndex < 0 || ModuleIndex >100) { help = false; while (help != true) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "hey, that's a invalid value, try again!" << endl; cout << "enter mark (0 - 100): " << endl; cin >> ModuleIndex; if ((ModuleIndex > 0) &&( ModuleIndex < 101)) { help = true; } } } return ModuleIndex; }
您需要允许用户在GetMarks中指定marks [i] / ModuleIndex的新值。清除cin后,从cin中读取一个新值。您还需要返回该值,以便可以使用该值而不是原始的超出范围值更新main的标记[i]。