垃圾留在cin缓冲区

时间:2013-01-13 22:54:06

标签: c++

我需要防止缓冲区中剩下的垃圾输入一个开关案例菜单的值,而不是在用户输入的菜单调用的函数中使用。

菜单代码

void menu()
{
bool done = false; 
string input;
while(!done)
{
    cout << "Welcome to the DVD database." << endl;
    cout << "1. Add A DVD" << endl;
    cout << "2. Delete a DVD." << endl;
    cout << "3. Edit a DVD." << endl;
    cout << "4. List By Category." << endl;
    cout << "5. Retrieve by a DVD by Title." << endl;
    cout << "6. Display collection by year" << endl;
    cout << "7. Display collection by title" << endl;
    cout << "-999. Exit program" << endl;
    cout << "Please choose an option by entering the corresponding number" << endl;
    cin >> input;
    int value = atoi(input.c_str());
    switch(value)
    {
        case 1:addDVD(); break;
        case 2:deleteDVD(); break;
       // case 3:editDVD(); break;
        case 4:listByCategory();break;
        case 6:displayByYear();break;
        case 7:displayByTitle();break;
        case -999: writeToFile(); exit(0); break;
        default : cout <<"Invalid entry"<< endl; break;
    }
}
}

void retrieveByTitle()
{
string search;
int size = database.size();
int index = 0;
bool found = false;
cin.ignore();
cout << "Please enter the title of the DVD you would like to retrieve: " << endl;
getline(cin,search);
cout << search;
while(!found && index<size)
{
    if(database.at(index)->getTitle().compare(search)==0)
    {
        cout << database.at(index)->toString();
        break;
    }
}
cout << endl;
}

如果在菜单中输入5,程序将跳过方法

中的用户输入

2 个答案:

答案 0 :(得分:0)

此代码有效,但如果您删除了“cin.ignore()”,它会删除由cin&gt;&gt;忽略的额外分隔符,则会出现同样的问题。操作者:

#include <iostream>
#include <climits>
using namespace std;

int main() {
    string a, b;
    while (true) {

        cout << "write 'x' to exit: " << endl;
        cin >> a;
        if (a == "x") {
            break;
        }       
        cout << "read '" << a << "'" << endl;

        cout << "now write a line: " << endl;
        cin.clear();          // clears cin status
        cin.ignore(INT_MAX);  // clears existing, unprocessed input

        getline(cin, a);
        cout << "read '" << a << "'" << endl;
    }

    return 0;
}

答案 1 :(得分:0)

在处理交互式用户输入时,您应该使用std :: getline()

每次点击&lt; enter&gt;时,std :: cin都会刷新到应用程序。所以这是你应该从用户那里读取数据的逻辑容器。

std::string answer;
std::cout << "Question:\n";
std::getline(std::cin, answer);

这可以获得用户在回答上一个问题时提供的所有内容。

获得输入后,您应该获得您认为输入的值。一旦你有了这个,你应该检查输入上是否有任何其他垃圾(如果有中止并重新尝试),否则验证你期望的数据。

如果您需要一个整数;

std::stringstream linestream(answer);
int               value;
std::string       junk;

if ((answer >> value)) && (!(answer >> junk)))
{
    // If you got data
    // and there was no junk on the line you are now good to go
}

在您的具体示例中,已经有一种简单的方法可以执行此操作:

std::getline(std::cin, input);
int value = boost::lexical_cast<int>(input);  // throws an exception if there is not
                                              // an int on the input (with no junk)