Do-while循环无法正常执行

时间:2017-11-23 04:57:14

标签: c++ function do-while

我不知道为什么我在这个简单的事情上遇到麻烦。我只是希望程序在用户输入Y或y后运行所有函数后,询问用户是否要再次重复该过程。当我运行程序并输入Y或y时,程序会循环,但它会记住之前的所有值,因此它会进入无限错误循环。

int main()
{
    //declare variables
    const int NUM_NAMES = 20;
    char repeat;
    int nameIndexLoc;
    string searchUser, 
        //array of unsorted elements
        names[NUM_NAMES] = { "Collins, Bill", "Smith, Bart", "Allen, Jim",
                             "Griffin, Jim", "Stamey, Marty", "Rose, Geri",
                             "Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
                             "Looney, Joe", "Wolfe, Bill", "James, Jean",
                             "Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
                             "Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
                             "Pike, Gordon", "Holland, Beth" };
    //do while to continue searching
    do
    {
        //calls function to sort list of names
        selectionSort(names, NUM_NAMES);
        //prints names after they have been sorted
        printSortedNames(names, NUM_NAMES);
        //gets the users name to search for in list
        searchUser = getName();
        //gets index of array where name is found
        nameIndexLoc = getNameIndex(names, NUM_NAMES, searchUser);
        //displays index location of name found
        displaySearchResults(nameIndexLoc);
        //prompt to try again
        cout <<"\n\nWould you like to do another search? (Y/y)" << endl
             << "Or anything else to quit: ";
        cin >> repeat;
    } while (repeat == 'Y'|| repeat == 'y');

    _getch();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果用户想要再次搜索,则问题出在我的主要权利之后。

do {

        //calls function to sort list of names
        selectionSort(names, NUM_NAMES);
        //prints names after they have been sorted
        printSortedNames(names, NUM_NAMES);
        //gets the users name to search for in list
        searchUser = getName();
        //gets index of array where name is found
        nameIndexLoc = getNameIndex(names, NUM_NAMES, searchUser);
        //displays index location of name found
        displaySearchResults(nameIndexLoc);
        //prompt to try again
        cout <<"\n\nWould you like to do another search? (Y/y)" << endl
            << "Or anything else to quit: ";
        cin >> repeat;
        cin.ignore();
    } while (repeat == 'Y'|| repeat == 'y');

添加cin.ignore();重复清除缓冲区后,允许程序正确运行。 我也可以将它添加到我的其他函数中以获得相同的结果。

string getName() {
    //declare variable
    string name;
    //gets user name to search for
    cout << "Enter a name to search for: ";
    cin.clear();
    cin.ignore();
    getline(cin, name);
    return name;
}

我会将它留在getName函数中,因为它看起来更整洁。