C ++ GetLine()问题,命令行程序

时间:2011-09-28 03:09:50

标签: c++ iostream getline cin

我正在为我的编程类编写这个程序,它有一堆愚蠢的约束,比如我必须使用嵌套if else语句,我必须使用cin.getLine()来获取玩家的名字。它应该抓住每个球员的名字并计算他们的击球率。

这不是整个程序,而是我遇到错误的部分。当我在命令提示符下运行它时,我可以很好地接收名字,但在那之后第二个cin.getline()不会读取任何输入。建议?

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    char name1[100], name2[100], name3[100];
    int numBat, numHit;
    double avg1, avg2, avg3;

    // Get Average for Player 1
    cout << "What's Your Name? ";
    cin.getline(name1, 100);

    cout << "How many times have you been at bat? ";
    cin >> numBat;

    if(numBat < 0 || numBat > 25)
    {
        cout << "ERROR ::: Number of Times at Bat Cannot Be Less Than 0 or Greater Than 25. Run Program Again." << endl;
        return 0;
    }
    else
    {

        cout << "How many times have you hit the ball? ";
        cin >> numHit;

        if(numHit < 0)
        {
            cout << "ERROR ::: Number Hit Cannot Be Less Than 0. Run Program Again." << endl;
            return 0;
        }
        else
        {
            // Calculate Average for Player 1
            avg1 = numHit / numBat;

            // Get Average for Player 2
            cout << "What's Your Name? ";
            cin.getline(name2, 100);

            cout << "How many times have you been at bat? ";
            cin >> numBat;

            cout << "How many times have you hit the ball? ";
            cin >> numHit;
                  }
         }
}

3 个答案:

答案 0 :(得分:1)

我认为这是一个缓冲问题。尝试在第二个cin之前刷新getline

cin.clear(); // clear the buffer
cin.sync();

如果不起作用,请尝试以下方法:

cin.ignore(256, '\n'); // ignore the endline and char(256)

答案 1 :(得分:0)

getline之后,您需要使用cout << endl;输出换行符。

答案 2 :(得分:0)

使用时

   cin >> numBat;

它没有读取换行符,所以下一个cin.getline()会读取并继续。

使用

cin >> numBat;
cin.ignore(80,'\n');