0

重複の可能性:
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;
    }
}
4

1 に答える 1

9

問題はここにあります:

cin >> options;

ユーザーがEnterキーを押したとき>>からのみ、()を抽出できます。cinしたがって、ユーザーが入力1 Enterすると、その行が実行されます。optionsはであるため、から1文字()をchar抽出し、に格納します。まだ何も消費していないため、はまだstdinバッファにあります。呼び出しに到達すると、バッファに最初に表示されるのは、入力の終わりを示す、であるため、すぐに空の文字列を返します。1cinoptionsEntergetlineEntergetline

それを修正する方法はたくさんあります。プログラムで使用しているモデルに適合する最も簡単な方法はcin、バッファ内の次の文字を無視するように指示することです。

cin >> options;
cin.ignore();
于 2011-05-10T17:00:54.443 に答える