开发者

C++ GetLine() Problem, Command Line Program

开发者 https://www.devze.com 2023-04-07 22:51 出处:网络
I am writing this program for my开发者_开发知识库 programming class and it has a bunch of stupid constraints like I must use nested if else statements and I have to use the cin.getLine() to get a play

I am writing this program for my开发者_开发知识库 programming class and it has a bunch of stupid constraints like I must use nested if else statements and I have to use the cin.getLine() to get a players name. It is supposed to grab the name of each player and calculate their batting average.

This is not the entire program but up to the part where I am having an error. When I run this in a command prompt I can recieve the first name fine, but after that the second cin.getline() does not read any input. Suggestions?

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


I think it's a buffer problem. Try to flush the cin before the second getline:

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

if that does not work, try something like this:

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


After the getline, you need to output a newline using cout << endl;.


When you use

   cin >> numBat;

It doesn't read the newline, so the next cin.getline() will read that and continue.

Use

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号