c ++ getline函数跳过cin

时间:2015-11-07 02:16:46

标签: c++ getline

不确定我的代码是怎么回事。问题在于我的getline功能。使用代码段:

string searchItem;
cout << "Enter the name of the item: ";
getline(cin, searchItem);
cout << searchItem << endl;

我已经将这个片段单独放在一个程序中并且它工作正常但是当我在我的代码中使用它时它会跳过它,好像根本没有cin一样。程序不会暂停以让用户输入任何内容。即使采用以下部分代码并将其放入不同的程序中,它仍然会做同样的事情。我不想把完整的代码放在一起,因为它是一个家庭作业。

#include <iostream> // used for standard I/O
#include <istream>
#include <fstream>  // used for file I/O
#include <string>   // used for string var
#include <vector>   // used for vectors
#include <iomanip>  // used for setprecision()


using namespace std;

void menu();

int main()
{
    menu();
}

void menu()
{
int mainMenuChoice;

cout << "Choose among the following options." << endl;
cout << "1: To see if an item is in the store." << endl;
cout << "2: To buy an item." << endl;
cout << "3. To check the price of an item." << endl;
cout << "4: To print the inventory." << endl;
cout << "9: To end the program." << endl;
cin >> mainMenuChoice;

cout << endl;
cout << endl;

// To see if an item is in the store.
if (mainMenuChoice == 1)
{
    int i = -1; // inventory location 
    string searchItem;
    cout << "Enter the name of the item: ";
    getline(cin, searchItem);
    cout << searchItem << endl;

    menu();
}
}

0 个答案:

没有答案