cin缓冲区清理,主体程序被强制结束循环

做练习题,每一道小题用函数写,并在主题程序中用循环结构调用。但是两个练习会要求输入字符 并多于需求。
cin缓冲区任然存在遗留的字符开头就是空字符,直接导致主程序结束,或者陷入死循环。

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int p5_8();
int p5_9();

int main()
{
    int num;
    cout << "code to use: ";
    cin >> num;
    while (num > 0)
    {
        if (num == 1)
            p5_8();
        else if (num == 2)
            p5_9();
        cout << "code to use: ";
        //cin.get();
        cin >> num;
    }
    return 0;
}

int p5_8()
{
    char word[100];
    int count = 0;
    cout << "Enter words (to stop, type the word done):" << endl;
    cin >> word;

    while (strcmp(word, "done") != 0)
    {
        if (bool(cin >> word) == true)
            count++;
    }

    cout << endl << "You entered a total of " << count << " words." << endl;
    //cin.sync();
    return 0;
}

int p5_9()
{

    string word;
    int count = 0;
    cout << "Enter words (to stop, type the word done):" << endl;
    cin >> word;

    while (word != "done")
    {
        if (bool(cin >> word) == true)
            count++;
    }

    cout << "You entered a total of " << count << " words." << endl;
    //cin.sync();
    return 0;
}

图片说明

尝试使用cin.sync()清理也没有效果。
请问如何解决问题,使主程序能够正常循环

你这个题目设计是用done这个词做结尾,如果不想这样,就得做修改,改规则,如果是输入一行以回车当结尾,这样做:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

void p5_8();
void p5_9();

int main()
{
    int num;
    cout << "code to use: ";
    cin >> num;
    while (num != 0)
    {
        if (num == 1)
            p5_8();
        else if (num == 2)
            p5_9();
        cout << "code to use: ";
        cin >> num;
    }
    return 0;
}

void p5_8()
{
    char word[100];
    int count = 0;
    cout << "Enter words (to stop, type the word done):" << endl;
    cin >> word;

    while (strcmp(word, "done") != 0)
    {
        if (bool(cin >> word) == true)
            count++;
    }

    cout << endl << "You entered a total of " << count << " words." << endl;
    cin.clear();
    cin.sync();
}

void p5_9()
{

    string word;
    int count = 0;
    cout << "Enter words (to stop, type the word done):" << endl;
    cin >> word;

    while (word != "done")
    {
        if (bool(cin >> word) == true)
            count++;
    }

    cout << "You entered a total of " << count << " words." << endl;
    cin.clear();
    cin.sync();
}

增加了两行
cin.clear();
cin.sync(); //或者用cin.ignore();