1

我有一个控制台应用程序,它会等待用户输入字符串。它必须是 getline,因为它可能包含空格。但它不等待输入,它会跳过它并运行函数。这是我的代码:

int main()
{
    vector<person> people;
    bool flag = true;
    int num_people = 0;
    //char*filename="names.txt";

    people = read_file();

    while(flag)
    {
        int sel = 0;
        string args;
        cout << "1 - Sök del av personnamn" << "\n" 
    << "2 - Sök städer" << "\n" << "3 - Avsluta" << endl;
    cin >> sel;
    if(sel == 1)
    {
                cout << "Mata in delen av personnamnet" << endl;
                getline(cin, args);
                print_result(find_in_names(people, args));
    }
    else if(sel == 2)
    {
                cout << "Mata in staden" << endl;
                getline(cin, args);
                args = lower_letters(args);
                print_result(find_person_from_city(people, args));
        }
    else if(sel==3)
    {
        flag=false;
    }
    else
    {
        cout << "FEL, TRYCK OM!" << endl;
    }
    }
}

运行没有错误,它只是跳过 getline 并且不让用户输入任何内容。

4

1 回答 1

5

这是使用该getline()功能的简单方法:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string name;
    int age;

    cout << "How old are you ?" << endl;
    cin >> age;

    cin.ignore();              // for avoiding trouble with 'name' when we're gonne use getline()

    cout << "What's your name ?" << endl;
    getline(cin, name); 

    system("PAUSE");
}

别忘了,如果你使用cinbefor getline(),你必须把这条线:

cin.ignore();

所以你的代码应该是这样的:

int main()
{
    vector<person> people;
    bool flag = true;
    int num_people = 0;
    //char*filename="names.txt";

    people = read_file();

    while(flag)
    {
        int sel = 0;
        string args;
        cout << "1 - Sök del av personnamn" << "\n" << "2 - Sök städer" << "\n" << "3 - Avsluta" << endl;
        cin >> sel;

        cin.ignore()

        if(sel == 1)
        {
            cout << "Mata in delen av personnamnet" << endl;
            getline(cin, args);
            print_result(find_in_names(people, args));
        }
        else if(sel == 2)
        {
            cout << "Mata in staden" << endl;
            getline(cin, args);
            args = lower_letters(args);
            print_result(find_person_from_city(people, args));
        }
        else if(sel==3)
        {
            flag=false;
        }
        else
        {
            cout << "FEL, TRYCK OM!" << endl;
        }
    }
}

这是一些文档http://www.cplusplus.com/reference/istream/istream/ignore/,希望对您有所帮助;

于 2013-02-24T21:21:50.940 回答