2013-02-24 71 views
1

我有一個控制檯應用程序,它等待用戶輸入一個字符串。它必須是getline,因爲它可以包含空格。但它不會等待輸入,它會跳過它並運行函數。這裏是我的代碼:不會等待getline C++

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,不讓用戶輸入任何東西。

+0

看起來與需要幫助相同。 cin正在離開返回鍵按下,正在通過getline()讀取它。 – 2013-02-24 20:31:23

回答

4

下面是使用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"); 
} 

別忘了,如果你使用cin befor 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; 
     } 
    } 
} 

這裏有一些doc http://www.cplusplus.com/reference/istream/istream/ignore/,希望它會有所幫助;