1

I have a console application that shopuld wait for the user to input a string. It has to be getline, because it could contain spaces. But it doesn't wait for input, it skips it and runs the functions anyway. Here's my code:

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;
    }
    }
}

Runs without errors, it just skips the getline and doesn't let the user input anything.

pimmen
  • 402
  • 4
  • 17

1 Answers1

5

Here is a simple way to use the getline() function :

#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");
}

Don't forget it, if you use cin befor getline(), you have to put the line :

cin.ignore();

So your code should looks like something like that :

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;
        }
    }
}

Here's some doc http://www.cplusplus.com/reference/istream/istream/ignore/, hope it'll help;

borderless
  • 948
  • 6
  • 5