2011-05-10 41 views
0

可能重复:
Need help with getline()为什么getline不会导致我预期的文本?

在下面的代码,我的函数getline完全跳过,不会提示输入。

#include <cstdlib> 
#include <iostream> 
#include <iomanip> 
#include <string> 
#include <istream> 

using namespace std; 

int main() 
{ 
    int UserTicket[8]; 
    int WinningNums[8]; 
    char options; 
    string userName; 

    cout << "LITTLETON CITY LOTTO MODEL: " << endl; 
    cout << "---------------------------" << endl; 
    cout << "1) Play Lotto " << endl; 
    cout << "q) Quit Program " << endl; 
    cout << "Please make a selection: " << endl; 

    cin >> options; 

    switch (options) 
    { 
    case 'q': 
     return 0; 
     break; 

    case '1': 
     { 
      cout << "Please enter your name please: " << endl; 
      getline(cin, userName); 
      cout << userName; 
     } 
     cin.get(); 
     return 0; 
    } 
} 
+1

它是如何不工作?在什么条件下?运行时错误?编译器错误?你想做什么?你能把它结晶到一个更小的例子吗? – 2011-05-10 16:55:58

+0

不错的方式让人们开始思考... – 2011-05-10 16:56:27

+2

也,这功课?如果是这样,它应该被贴上标签。 – 2011-05-10 16:56:40

回答

9

的问题是在这里:

cin >> options; 

只能从cin提取物(>>),当用户点击进入。因此,用户键入 输入并执行该行。由于optionschar,它从cin中提取单个字符(1)并将其存储在options中。 输入仍然在stdin缓冲区中,因为还没有消耗它。当你进入getline调用时,它在缓冲区中看到的第一件事是输入,这标志着输入的结束,因此getline立即返回一个空字符串。

有很多方法可以解决它;可能是你正在使用你的程序的模型拟合的最简单的方法就是告诉cin忽略下一个字符的缓冲区:

cin >> options; 
cin.ignore(); 
+0

谢谢,我忘了把cin.ignore(); – 2011-05-10 17:03:33

+0

+1按钮。我以前从未见过。 – 2011-05-10 17:27:09

相关问题